As an alternative to ftp_fget, we could have used ftp_get, which has the following prototype: int ftp_get int ftp_connection, string localfile_path, string remotefile_path, int mode This
Trang 1There are two modes for an FTP transfer, ASCII and binary The ASCII mode is used for
trans-ferring text files (that is, files that consist solely of ASCII characters), and the binary mode,
used for transferring everything else PHP’s FTP library comes with two predefined constants,
FTP_ASCIIand FTP_BINARY, that represent these two modes You need to decide which mode
fits your file type, and pass the corresponding constant to ftp_fget()as the fourth parameter
In this case we are transferring a zip file, and so we have used the FTP_BINARYmode
The ftp_fget()function returns trueif all goes well, or falseif an error is encountered We
store the result in $success, and let the user know how it went
After the download has been attempted, we close the local file using the fclose()function
As an alternative to ftp_fget(), we could have used ftp_get(), which has the following
prototype:
int ftp_get (int ftp_connection, string localfile_path,
string remotefile_path, int mode)
This function works in much the same way as ftp_fget(), but does not require the local file
to be open You pass it the system filename of the local file you would like to write to rather
than a file handle
Note that there is no equivalent to the FTP command mget, which can be used to download
multiple files at a time You must instead make multiple calls to ftp_fget()or ftp_get()
Closing the Connection
After we have finished with the FTP connection, you should close it using the ftp_quit()
function:
ftp_quit($conn);
You should pass this function the handle for the FTP connection
Uploading Files
If you want to go the other way, that is, copy files from your server to a remote machine, you
can use two functions that are basically the opposite of ftp_fget()and ftp_get() These
functions are called ftp_fput()and ftp_put() They have the following prototypes:
int ftp_fput (int ftp_connection, string remotefile_path, int fp, int mode)
int ftp_put (int ftp_connection, string remotefile_path,
string localfile_path, int mode)
The parameters are the same as for the _getequivalents
17
Trang 2Avoiding Timeouts
One problem you might face when FTPing files is exceeding the maximum execution time You will know whether this happens because PHP will give you an error message This is especially likely to occur if your server is running over a slow or congested network, or if you are downloading a large file, such as a movie clip
The default value of the maximum execution time for all PHP scripts is defined in the php.ini
file By default, it’s set to 30 seconds This is designed to catch scripts that are running out of control However, when you are FTPing files, if your link to the rest of the world is slow, or if the file is large, the file transfer could well take longer than this
Fortunately, we can modify the maximum execution time for a particular script using the
set_time_limit()function Calling this function resets the maximum number of seconds the script is allowed to run, starting from the time the function is called For example, if you call
set_time_limit(90);
then the script will be able to run for another 90 seconds from the time the function is called
Using Other FTP Functions
There are a number of other useful FTP functions in PHP
The function ftp_size()can tell you the size of a file on a remote server It has the following prototype:
int ftp_size(int ftp_connection, string remotefile_path)
This function returns the size of the remote file in bytes, or -1 if there is an error This is not supported by all FTP servers
One handy use of ftp_size()is to work out what maximum execution time to set for a partic-ular transfer Given the file size and the speed of your connection, you can take a guess as to how long the transfer ought to take, and use the set_time_limit()function accordingly You can get and display a list of files in a directory on a remote FTP server with the following code:
$listing = ftp_nlist($conn, “$directory_path”);
foreach ($listing as $filename) echo “$filename <br>”;
This code uses the ftp_nlist()function to get a list of names of files in a particular directory
Trang 3In terms of other FTP functions, almost anything that you can do from an FTP command line,
you can do with the FTP functions You can find the specific functions corresponding to each
FTP command in the PHP online manual at
http://php.net/manual/ref.ftp.php
The exception is mget (multiple get), but you can use ftp_nlist()to get a list of files and
then fetch them as required
Generic Network Communications with cURL
PHP (from version 4.0.2 onwards) has a set of functions that acts as an interface to cURL, the
Client URL library functions from libcurl, written by Daniel Stenberg
Previously in this chapter, we looked at using the fopen()function and the file-reading
func-tions to read from a remote file using HTTP This is pretty much the limit of what you can do
with fopen() We’ve also seen how to make FTP connections using the FTP functions
The cURL functions enable you to make connections using FTP, HTTP, HTTPS, Gopher,
Telnet, DICT, FILE, and LDAP You can also use certificates for HTTPS, send HTTP POST
and HTTP GET parameters, upload files via FTP upload or HTTP upload, work through
prox-ies, set cookprox-ies, and perform simple HTTP user authentication
In other words, just about any kind of network connection that you’d like to make can be done
using cURL
To use cURL with PHP, you will need to download libcurl, compile it, and run PHP’s
configurescript with the with-curl=[path]option The directory in pathshould be the
one that contains the lib and include directories on your system You can download the library
from
http://curl.haxx.se/
Be aware that you will need a version of cURL from 7.0.2-beta onwards to work with PHP
There are only a few simple functions to master in order to use the power of cURL The
typi-cal procedure for using it is
1 Set up a cURL session with a call to the curl_init()function
2 Set any parameters for transfer with calls to the curl_setopt()function This is where
you set options such as the URL to connect to, any parameters to send to that URL, or the destination of the output from the URL
3 When everything is set up, call curl_exec()to actually make the connection
4 Close the cURL session by calling curl_close()
17
Trang 4The only things that change with the application are the URL that you connect to and the para-meters you set with curl_opt() There are a large number of these that can be set
Some typical applications of cURL are
• Downloading pages from a server that uses HTTPS (because fopen()can’t be used for this purpose)
• Connecting to a script that normally expects data from an HTML form using POST
• Writing a script to send multiple sets of test data to your scripts and checking the output
We will consider the first example—it’s a simple application that can’t be done another way This example, shown in Listing 17.5, will connect to the Equifax Secure Server via HTTPS, and write the file it finds there to a file on our Web server
LISTING 17.5 https-curl.php—Script to Make HTTPS Connections
<?
echo “<h1>HTTPS transfer with cURL</h1>”;
$outputfile = “$DOCUMENT_ROOT/ /writable/equifax.html”;
$fp = fopen($outputfile, “w”);
echo “Initializing cURL session <br>”;
$ch = curl_init();
echo “Setting cURL options <br>”;
curl_setopt ($ch, CURLOPT_URL, “https://equifaxsecure.com”);
curl_setopt ($ch, CURLOPT_FILE, $fp);
echo “Executing cURL session <br>”;
curl_exec ($ch);
echo “Ending cURL session <br>”;
curl_close ($ch);
fclose($fp);
?>
Let’s go through this script We begin by opening a local file using fopen() This is where we are going to store the page we transfer from the secure connection
When this is done, we need to create a cURL session using the curl_init()function:
$ch = curl_init();
This function returns a handle for the cURL session You can call it like this, with no parame-ters, or optionally you can pass it a string containing the URL to connect to You can also set the URL using the curl_setopt()function, which is what we have done in this case:
curl_setopt ($ch, CURLOPT_URL, “https://equifaxsecure.com”);
curl_setopt ($ch, CURLOPT_FILE, $fp);
Trang 5The curl_setopt()function takes three parameters The first is the session handle, the second
is the name of the parameter to set, and the third is the value to which you would like the
para-meter set
In this case we are setting two options The first is the URL that we want to connect to This is
the CURLOPT_URLparameter The second one is the file where we want the data from the
con-nection to go If you don’t specify a file, the data from the concon-nection will go to standard
output—usually the browser In this case we have specified the file handle of the output file we
just opened
When the options are set, we tell cURL to actually make the connection:
curl_exec ($ch);
Here, this will open a connection to the URL we have specified, download the page, and store
it in the file pointed to by $fp
After the connection has been made, we need to close the cURL session, and close the file we
wrote to:
curl_close ($ch);
fclose($fp);
That’s it for this simple example
You might find it worthwhile to look at the Snoopy class, available from
http://snoopy.sourceforge.net/
This class provides Web client functionality through cURL
Further Reading
We’ve covered a lot of ground in this chapter, and as you might expect, there’s a lot of material
out there on these topics
For information on the individual protocols and how they work, you can consult the RFCs at
http://www.rfc-editor.org/
You might also find some of the protocol information at the World Wide Web Consortium
interesting:
http://www.w3.org/Protocols/
You can also try consulting a book on TCP/IP such as Computer Networks by Andrew
Tanenbaum
17
Trang 6The cURL Web site has some tips on how to use the command line versions of the cURL func-tions, and these are fairly easily translated into the PHP versions:
http://curl.haxx.se/docs/httpscripting.shtml
Next
We’ll move on to Chapter 18, “Managing the Date and Time,” and look at PHP’s libraries of date and calendar functions You’ll see how to convert from user-entered formats to PHP for-mats to MySQL forfor-mats, and back again.
Trang 718
Managing the Date and Time
Trang 8In this chapter, we’ll discuss checking and formatting the date and time and converting between date formats This is especially important when converting between MySQL and PHP date formats, UNIX and PHP date formats, and dates entered by the user in an HTML form We’ll cover
• Getting the date and time in PHP
• Converting between PHP and MySQL date formats
• Calculating dates
• Using the calendar functions
Getting the Date and Time from PHP
Way back in Chapter 1, “PHP Crash Course,” we talked about using the date()function to get and format the date and time from PHP We’ll talk about it and some of PHP’s other date and time functions in a little more detail now
Using the date() Function
As you might recall, the date()function takes two parameters, one of them optional The first one is a format string, and the second, optional one is a UNIX time stamp If you don’t specify
a time stamp, then date()will default to the current date and time It returns a formatted string representing the appropriate date
A typical call to the date function could be
echo date(“jS F Y”);
This will produce a date of the format “27th August 2000”
The format codes accepted by date are listed in Table 18.1
TABLE 18.1 Format Codes for PHP’s date() Function
Code Description
a Morning or afternoon, represented as two lowercase characters, either
“am” or “pm”
A Morning or afternoon, represented as two uppercase characters, either
“AM” or “PM”
B Swatch Internet time, a universal time scheme More information is
avail-able at http://swatch.com/internettime/internettime.php3
d Day of the month as a 2-digit number with a leading zero Range is from
“01” to “31”
Trang 9D Day of the week in 3-character abbreviated text format Range is from
“Mon” to “Sun”
F Month of the year in full text format Range is from “January” to
“December”
g Hour of the day in 12-hour format without leading zeroes Range is from
“1” to “12”
G Hour of the day in 24-hour format without leading zeroes Range is from
“0” to “23”
h Hour of the day in 12-hour format with leading zeroes Range is from
“01” to “12”
H Hour of the day in 24-hour format with leading zeroes Range is from
“00” to “23”
i Minutes past the hour with leading zeroes Range is from “00” to “59”
I Daylight savings time, represented as a Boolean value This will return
“1” if the date is in daylight savings and “0” if it is not
j Day of the month as a number without leading zeroes Range is from “1”
to “31”
l Day of the week in full text format Range is from “Monday” to
“Sunday”
L Leap year, represented as a Boolean value This will return “1” if the date
is in a leap year and “0” if it is not
m Month of the year as a 2-digit number with leading zeroes Range is from
“01” to “12”
M Month of the year in 3-character abbreviated text format Range is from
“Jan” to “Dec”
n Month of the year as a number without leading zeroes Range is from “1”
to “12”
s Seconds past the minute with leading zeroes Range is from “00” to “59”
S Ordinal suffix for dates in 2-character format This can be “st”, “nd”,
“rd”, or “th”, depending on the number it is after
t Total number of days in the date’s month Range is from “28” to “31”
T Timezone setting of the server in 3-character format, for example, “EST”
U Total number of seconds from 1 January 1970 to this time; a.k.a., a
UNIX time stamp for this date
18
TABLE 18.1 Continued
Code Description
Trang 10w Day of the week as a single digit Range is from “0” (Sunday) to “6”
(Saturday)
y Year in 2-digit format, for example, “00”
Y Year in 4-digit format, for example, “2000”
z Day of the year as a number Range is “0” to “365”
Z Offset for the current timezone in seconds Range is “-43200” to “43200”
Dealing with UNIX Time Stamps
The second parameter to the date()function is a UNIX time stamp
In case you are wondering exactly what this means, most UNIX systems store the current time and date as a 32-bit integer containing the number of seconds since midnight, January 1, 1970, GMT, also known as the UNIX Epoch This can seem a bit esoteric if you are not familiar with
it, but it’s a standard
UNIX timestamps are a compact way of storing a date and time, but it is worth noting that they
do not suffer from the year 2000 (Y2K) problem that affects some other compact or abbrevi-ated date formats If your software is still in use in 2038, there will be similar problems though As timestamps do not have a fixed size, but are tied to the size of a C long, which is at least 32 bits, the most likely solution is that by 2038, your compiler will use a larger type Even if you are running PHP on a Windows server, this is still the format that is used by
date()and a number of other PHP functions
If you want to convert a date and time to a UNIX time stamp, you can use the mktime() func-tion This has the following prototype:
int mktime (int hour, int minute, int second, int month,
int day, int year [, int is_dst])
The parameters are fairly self-explanatory, with the exception of the last one,is_dst, which
represents whether the date was in daylight savings time or not You can set this to 1if it was,
0if it wasn’t, or -1(the default value) if you don’t know This is optional so you will rarely use it anyway
The main trap to avoid with this function is that the parameters are in a fairly unintuitive order The ordering doesn’t lend itself to leaving out the time If you are not worried about the time,
TABLE 18.1 Continued
Code Description