PHP Function Reference

PHP ftp_fget() Function



The PHP ftp_fget() function downloads a file from the FTP server, and saves it into an open local file.

Syntax

ftp_fget(ftp, open_file, server_file, 
          mode, offset)

Parameters

ftp Required. Specify the FTP connection to use.
open_file Required. Specify the open file pointer in which we store the data.
server_file Required. Specify the server file to download.
mode Optional. Specify the transfer mode. Must be either FTP_ASCII or FTP_BINARY.
offset Optional. Specify the position in the remote file to start downloading from.

Return Value

Returns true on success or false on failure.

Example:

The example below shows the usage of ftp_fget() function.

<?php
//FTP server to use
$ftp_server = "ftp.example.com";

//username for the FTP Connection
$ftp_user = "user";
  
//password for the user
$ftp_pass = "password";
  
//set up a connection or die 
$ftp = ftp_connect($ftp_server)
    or die("Could not connect to $ftp_server");
   
if($ftp) {
  echo "Successfully connected to $ftp_server!\n";
 
  //trying to login
  if(@ftp_login($ftp, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";

    //local open file pointer in which 
    //we store the data
    $open_file = fopen("local_demo.txt", "w");
      
    //server file path which 
    //need to be downloaded
    $server_file = "server_demo.txt";
      
    //downloading the specified server file
    //and saving it to open local file
    if (ftp_fget($ftp, $open_file, 
                 $server_file, FTP_ASCII)) {
      echo "Successfully written to $open_file\n";
    } else {
      echo "Error while downloading $server_file\n";
    }

    //closing the file pointer
    fclose($open_file);
    
  } else {
    echo "Couldn't connect as $ftp_user\n";
  }
 
  //close the connection
  if(ftp_close($ftp)) {
    echo "Connection closed successfully!\n"; 
  } 
}
?>

The output of the above code will be:

Successfully connected to ftp.example.com!
Connected as user@ftp.example.com
Successfully written to local_demo.txt
Connection closed successfully!

❮ PHP FTP Reference