<form method=post action=”directory_submit.php”> URL: <input type=text name=”url” size=30 value=”http://”><br> Email contact: <input type=text name=”email” size=23><br> <input type=”submit” name=”Submit site”> </form> </body> </html> This is a very simple form—the rendered version, with some sample data entered, is shown in Figure 17.2. Using Network and Protocol Functions C HAPTER 17 17 USING NETWORK AND PROTOCOL FUNCTIONS 375 LISTING 17.2 Continued FIGURE 17.2 Directory submissions typically require your URL and some contact details so directory administrators can notify you when your site is added to the directory. When the submit button is pressed, we want to check, first, that the URL is hosted on a real machine, and, second, that the host part of the email address is also on a real machine. We have written a script to check these things, and the output is shown in Figure 17.3. FIGURE 17.3 This version of the script displays the results of checking the hostnames for the URL and email address—a production version might not display these results, but it is interesting to see the information returned from our checks. 22 7842 CH17 3/6/01 3:39 PM Page 375 The script that performs these checks uses two functions from the PHP network functions suite—gethostbyname() and getmxrr(). The full script is shown in Listing 17.3. LISTING 17.3 directory_submit.php—Script to Verify URL and Email Address <html> <head> <title>Site submission results</title> </head> <body> <h1>Site submission results</h1> <? // Check the URL $url = parse_url($url); $host = $url[host]; if(!($ip = gethostbyname($host))) { echo “Host for URL does not have valid IP”; exit; } echo “Host is at IP $ip <br>”; // Check the email address $email = explode(“@”, $email); $emailhost = $email[1]; if (!getmxrr($emailhost, $mxhostsarr)) { echo “Email address is not at valid host”; exit; } echo “Email is delivered via: “; foreach ($mxhostsarr as $mx) echo “$mx “; // If reached here, all ok echo “<br>All submitted details are ok.<br>”; echo “Thank you for submitting your site.<br>” .”It will be visited by one of our staff members soon.” // In real case, add to db of waiting sites Advanced PHP Techniques P ART IV 376 22 7842 CH17 3/6/01 3:39 PM Page 376 ?> </body> </html> Lets’ go through the interesting parts of this script. First, we take the URL and apply the parse_url() function to it. This function returns an associative array of the different parts of an URL. The available pieces of information are the scheme, user, pass, host, port, path, query, and fragment. Typically, you aren’t going to need all of these, but here’s an example of how they make up an URL. Given an URL such as http://nobody:secret@bigcompany.com:80/script.php?variable=value#anchor the values of each of the parts of the array would be • scheme: http:// • user: nobody • pass: secret • host: bigcompany.com • port: 80 • path: script.php • query: variable=value • fragment: anchor In our script, we only want the host information, so we pull it out of the array as follows: $url = parse_url($url); $host = $url[host]; After we’ve done this, we can get the IP address of that host, if it is in the DNS. We can do this using the gethostbyname() function, which will return the IP if there is one, or false if not: $ip = gethostbyname($host) You can also go the other way using the gethostbyaddr() function, which takes an IP as para- meter and returns the hostname. If you call these functions in succession, you might well end up with a different hostname from the one you began with. This can mean that a site is using a virtual hosting service. Using Network and Protocol Functions C HAPTER 17 17 USING NETWORK AND PROTOCOL FUNCTIONS 377 LISTING 17.3 Continued 22 7842 CH17 3/6/01 3:39 PM Page 377 If the URL is valid, we then go on to check the email address. First, we split it into username and hostname with a call to explode(): $email = explode(“@”, $email); $emailhost = $email[1]; When we have the host part of the address, we can check to see if there is a place for that mail to go using the getmxrr() function: getmxrr($emailhost, $mxhostsarr) This function returns the set of MX (Mail Exchange) records for an address in the array you supply at $mxhostarr. An MX record is stored at the DNS and is looked up like a hostname. The machine listed in the MX record isn’t necessarily the machine where the email will eventually end up. Instead it’s a machine that knows where to route that email. (There can be more than one, hence this function returns an array rather than a hostname string.) If we don’t have an MX record in the DNS, then there’s nowhere for the mail to go. If all these checks are okay, we can put this form data in a database for later review by a staff member. In addition to the functions we’ve just used, you can use the more generic function checkdnsrr(), which takes a hostname and returns true if there is any record of it in the DNS. Using FTP File Transfer Protocol, or FTP, is used to transfer files between hosts on a network. Using PHP, you can use fopen() and the various file functions with FTP as you can with HTTP connec- tions, to connect to and transfer files to and from an FTP server. However, there is also a set of FTP-specific functions that comes with the standard PHP install. These functions are not built in to the standard install by default. In order to use them under UNIX, you will need to run the PHP configure program with the enable-ftp option, and then rerun make. To use the FTP functions with the Win32 binary, you will need to add the line extension=php_ftp.dll under the “Windows Extensions” section of your php.ini file. (For more details on configur- ing PHP, see Appendix A, “Installing PHP 4 and MySQL.”) Advanced PHP Techniques P ART IV 378 22 7842 CH17 3/6/01 3:39 PM Page 378 Using FTP to Back Up or Mirror a File The FTP functions are useful for moving and copying files from and to other hosts. One com- mon use you might make of this is to back up your Web site or mirror files at another location. We will look at a simple example using the FTP functions to mirror a file. This script is shown in Listing 17.4. LISTING 17.4 ftpmirror.php—Script to Download New Versions of a File from an FTP Server <html> <head> <title>Mirror update</title> </head> <body> <h1>Mirror update</h1> <? // set up variables - change these to suit application $host = “ftp.cs.rmit.edu.au”; $user = “anonymous”; $password = “laura@tangledweb.com.au”; $remotefile = “/pub/tsg/ttssh14.zip”; $localfile = “$DOCUMENT_ROOT/ /writable/ttssh14.zip”; // connect to host $conn = ftp_connect(“$host”); if (!$conn) { echo “Error: Could not connect to ftp server<br>”; exit; } echo “Connected to $host.<br>”; // log in to host @ $result = ftp_login($conn, $user, $pass); if (!$result) { echo “Error: Could not log on as $user<br>”; ftp_quit($conn); exit; } echo “Logged in as $user<br>”; // check file times to see if an update is required Using Network and Protocol Functions C HAPTER 17 17 USING NETWORK AND PROTOCOL FUNCTIONS 379 22 7842 CH17 3/6/01 3:39 PM Page 379 echo “Checking file time <br>”; if (file_exists($localfile)) { $localtime = filemtime($localfile); echo “Local file last updated “; echo date(“G:i j-M-Y”, $localtime); echo “<br>”; } else $localtime=0; $remotetime = ftp_mdtm($conn, $remotefile); if (!($remotetime >= 0)) { // This doesn’t mean the file’s not there, server may not support mod time echo “Can’t access remote file time.<br>”; $remotetime=$localtime+1; // make sure of an update } else { echo “Remote file last updated “; echo date(“G:i j-M-Y”, $remotetime); echo “<br>”; } if (!($remotetime > $localtime)) { echo “Local copy is up to date.<br>”; exit; } // download file echo “Getting file from server <br>”; $fp = fopen ($localfile, “w”); if (!$success = ftp_fget($conn, $fp, $remotefile, FTP_BINARY)) { echo “Error: Could not download file”; ftp_quit($conn); exit; } fclose($fp); echo “File downloaded successfully”; // close connection to host ftp_quit($conn); Advanced PHP Techniques P ART IV 380 LISTING 17.4 Continued 22 7842 CH17 3/6/01 3:39 PM Page 380 ?> </body> </html> The output from running this script on one occasion is shown in Figure 17.4. Using Network and Protocol Functions C HAPTER 17 17 USING NETWORK AND PROTOCOL FUNCTIONS 381 LISTING 17.4 Continued FIGURE 17.4 The FTP mirroring script checks whether the local version of a file is up-to-date, and downloads a new version if not. This is quite a generic script. You’ll see that it begins by setting up some variables: $host = “ftp.cs.rmit.edu.au”; $user = “anonymous”; $password = “laura@tangledweb.com.au”; $remotefile = “/pub/tsg/ttssh14.zip”; $localfile = “$DOCUMENT_ROOT/ /writable/ttssh14.zip”; The $host variable should contain the name of the FTP server you want to connect to, and the $user and $password correspond to the username and password you would like to log in with. Many FTP sites support what is called anonymous login, that is, a freely available username that anybody can use to connect. No password is required, but it is a common courtesy to sup- ply your email address as a password so that the system’s administrators can see where their users are coming from. We have followed this convention here. The $remotefile variable contains the path to the file we would like to download. In this case we are downloading and mirroring a local copy of Tera Term SSH, an SSH client for Windows. (SSH stands for secure shell. This is an encrypted form of Telnet.) The $localfile variable contains the path to the location where we are going to store the downloaded file on our machine. You should be able to change these variables to adapt this script for your purposes. 22 7842 CH17 3/6/01 3:39 PM Page 381 The basic steps we follow in this script are the same as if you wanted to manually FTP the file from a command line interface: 1. Connect to the remote FTP server. 2. Log in (either as a user or anonymous). 3. Check whether the remote file has been updated. 4. If it has, download it. 5. Close the FTP connection. Let’s take each of these in turn. Connecting to the Remote FTP Server This step is equivalent to typing ftp hostname at a command prompt on either a Windows or UNIX platform. We accomplish this step in PHP with the following code: $conn = ftp_connect(“$host”); if (!$conn) { echo “Error: Could not connect to ftp server<br>”; exit; } echo “Connected to $host.<br>”; The function call here is to ftp_connect(). This function takes a hostname as parameter, and returns either a handle to a connection, or false if a connection could not be established. The function can also takes the port number on the host to connect to as an optional second para- meter. (We have not used this here.) If you don’t specify a port number, it will default to port 21, the default for FTP. Logging In to the FTP Server The next step is to log in as a particular user with a particular password. You can achieve this using the ftp_login() function: @ $result = ftp_login($conn, $user, $pass); if (!$result) { echo “Error: Could not log on as $user<br>”; ftp_quit($conn); exit; } echo “Logged in as $user<br>”; Advanced PHP Techniques P ART IV 382 22 7842 CH17 3/6/01 3:39 PM Page 382 The function takes three parameters: an FTP connection (obtained from ftp_connect()), a username, and a password. It will return true if the user can be logged in, and false if he can’t. You will notice that we put an @ symbol at the start of the line to suppress errors. We do this because, if the user cannot be logged in, you will get a PHP warning in your browser win- dow. You can catch the error as we have done here by testing $result, and supplying your own, more user-friendly error message. Notice that if the login attempt fails, we actually close the FTP connection using ftp_quit()—more on this in a minute. Checking File Update Times Given that we are updating a local copy of a file, it is sensible to check whether the file needs updating first because you don’t want to have to re-download a file, particularly a large one, if it’s up to date. This will avoid unnecessary network traffic. Let’s look at the code that does this. First, we check that we have a local copy of the file, using the file_exists() function. If we don’t then obviously we need to download the file. If it does exist, we get the last modified time of the file using the filemtime() function, and store it in the $localtime variable. If it doesn’t exist, we set the $localtime variable to 0 so that it will be “older” than any possible remote file modification time: echo “Checking file time <br>”; if (file_exists($localfile)) { $localtime = filemtime($localfile); echo “Local file last updated “; echo date(“G:i j-M-Y”, $localtime); echo “<br>”; } else $localtime=0; (You can read more about the file_exists() and filemtime() functions in Chapter 2 and Chapter 16, “Interacting with the File System and the Server,” respectively.) After we have sorted out the local time, we need to get the modification time of the remote file. You can get this using the ftp_mdtm() function: $remotetime = ftp_mdtm($conn, $remotefile); This function takes two parameters—the FTP connection handle, and the path to the remote file—and returns either the UNIX time stamp of the time the file was last modified, or -1 if there is an error of some kind. Not all FTP servers support this feature, so we might not get a Using Network and Protocol Functions C HAPTER 17 17 USING NETWORK AND PROTOCOL FUNCTIONS 383 22 7842 CH17 3/6/01 3:39 PM Page 383 useful result from the function. In this case, we choose to artificially set the $remotetime vari- able to be “newer” than the $localtime variable by adding 1 to it. This will ensure that an attempt is made to download the file: if (!($remotetime >= 0)) { // This doesn’t mean the file’s not there, server may not support mod time echo “Can’t access remote file time.<br>”; $remotetime=$localtime+1; // make sure of an update } else { echo “Remote file last updated “; echo date(“G:i j-M-Y”, $remotetime); echo “<br>”; } When we have both times, we can compare them to see whether we need to download the file or not: if (!($remotetime > $localtime)) { echo “Local copy is up to date.<br>”; exit; } Downloading the File At this stage we will try to download the file from the server: echo “Getting file from server <br>”; $fp = fopen ($localfile, “w”); if (!$success = ftp_fget($conn, $fp, $remotefile, FTP_BINARY)) { echo “Error: Could not download file”; fclose($fp); ftp_quit($conn); exit; } fclose($fp); echo “File downloaded successfully”; We open a local file using fopen() as we have seen previously. After we have done this, we call the function ftp_fget(), which attempts to download the file and store in a local file. This function takes four parameters. The first three are straightforward—the FTP connection, the local file handle, and the path to the remote file. The fourth parameter is the FTP mode. Advanced PHP Techniques P ART IV 384 22 7842 CH17 3/6/01 3:39 PM Page 384 . your php. ini file. (For more details on configur- ing PHP, see Appendix A, “Installing PHP 4 and MySQL. ”) Advanced PHP Techniques P ART IV 378 22 7842 CH17 3/6/01 3:39 PM Page 378 Using FTP to. Remote FTP Server This step is equivalent to typing ftp hostname at a command prompt on either a Windows or UNIX platform. We accomplish this step in PHP with the following code: $conn = ftp_connect(“$host”); if. need to run the PHP configure program with the enable-ftp option, and then rerun make. To use the FTP functions with the Win32 binary, you will need to add the line extension =php_ ftp.dll under the