How to Download File on the FTP Server Using PHP

    Today we will see how to download file on the ftp server using php. Many time we have requirment to retrieve file from the FTP serverso here i will so you file download in ftp using ftp fget function, ftp_get() function is used to download file from the FTP server.

    The ftp_get() function retrieves a remote file from the FTP server and save it into an open local file.

     

Syntax : 
ftp_fget(ftp_conn, open_file, server_file, mode, startpos);
Parameters : 

    ftp_conn - ftp_conn is required parameter and it is use to specifies the FTP connection.

    open_file - open_file is required parameter and it is use to specifies open local file in which we store the data.

    server_file - local_file is required parameter and it is use to specifies the server file to download.

    mode - mode is optional parameter and it is use to specifies the transfer mode. It has 2 possible values: 1) FTP_ASCII 2) FTP_BINARY.

    startpos - startpos is optional parameter and it is use to specifies the position in the remote file to start download from.

Example :
<?php
// connect to FTP server
$ftp_server = "ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");

// login to FTP server
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

$server_file = "somefile.txt";

// open local file to write to
$local_file = "local.txt";
$fp = fopen($local_file,"w");

// download server file and save it to open local file
if (ftp_fget($ftp_conn, $fp, $server_file, FTP_ASCII, 0))
  {
  echo "Successfully written to $local_file.";
  }
else
  {
  echo "Error downloading $server_file.";
  }

// close connection and file handler
ftp_close($ftp_conn);
fclose($fp);
?>
Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan