FTP: Downloading a File


What if you want to move around an FTP site and download files? To change to a directory on an FTP site after you're logged in, use ftp_chdir:

 ftp_chdir(resource ftp_stream, string directory) 

This function changes your current directory on the FTP site to the specified directory. It returns trUE on success or FALSE on failure.

How about getting a file from the new directory? For that, use ftp_get:

 ftp_get(resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos]) 

This function retrieves remote_file from the FTP server and saves it to local_file locally (which can include a pathname). The transfer mode specified must be either FTP_ASCII or FTP_BINARY. It returns trUE on success or FALSE on failure. Here's an example, where we're connecting to an FTP site and downloading a file, a.php, storing it locally as script.php. We connect to the FTP site and use ftp_get to retrieve the file, testing the results like this:

 $connect = ftp_connect("ftp.ispname.com"); $result = ftp_login($connect, "username", "password"); if(!$result){     echo "Could not connect.";     exit; } $result = ftp_get($connect, "script.php", "a.php", FTP_ASCII); if($result){     echo "Got the file."; } else {     echo "Did not get the file."; } 

You can see the whole thing in phpftpget.php, Example 9-5.

Example 9-5. Downloading a file, phpftpget.php
 <HTML>     <HEAD>         <TITLE>             Getting a file with FTP         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Getting a file with FTP</H1>             Downloading the file....             <BR>             <?php                 $connect = ftp_connect("ftp.ispname.com");                 $result = ftp_login($connect, "username", "password");                 if(!$result){                     echo "Could not connect.";                     exit;                 }                 $result = ftp_get($connect, "script.php", "a.php", FTP_ASCII);                 if($result){                     echo "Got the file.";                 }                 else {                     echo "Did not get the file.";                 }                 ftp_close($connect);             ?>          </CENTER>     <BODY> </HTML> 

The results appear in Figure 9-6, where we've successfully downloaded the file.

Figure 9-6. Downloading a file.


Note that this stores the file in the same directory as phpftpget.php; if you want to store it elsewhere, include a path when you give the name of the local file.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net