Upload and Download files with FTP in PHP

By: David Sklar Emailed: 1646 times Printed: 2120 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

You want to transfer files using FTP. Use PHP's built-in FTP functions:

$c = ftp_connect('ftp.example.com')     or die("Can't connect");
ftp_login($c, $username, $password)     or die("Can't login");
ftp_put($c, $remote, $local, FTP_ASCII) or die("Can't transfer");
ftp_close($c);                          or die("Can't close");

You can also use the cURL extension:

$c = curl_init("ftp://$username:$password@ftp.example.com/$remote");
// $local is the location to store file on local machine
$fh = fopen($local, 'w') or die($php_errormsg); 
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);

FTP stands for File Transfer Protocol and is a method of exchanging files between one computer and another. Unlike with HTTP servers, it's easy to set up an FTP server to both send and receive files.

Using the built-in FTP functions doesn't require additional libraries, but you must specifically enable them with --enable-ftp. Because these functions are specialized to FTP, they're easy to use when transferring files.

All FTP transactions begin with establishing a connection from your computer, the local client, to another computer, the remote server:

$c = ftp_connect('ftp.example.com')     or die("Can't connect");

Once connected, you need to send your username and password; the remote server can then authenticate you and allow you to enter:

ftp_login($c, $username, $password)     or die("Can't login");

Some FTP servers support a feature known as anonymous FTP. Under anonymous FTP, users can log in without an account on the remote system. When you use anonymous FTP, your username is anonymous, and your password is your email address.

Here's how to transfer files with ftp_put( ) and ftp_get( ):

ftp_put($c, $remote, $local,  FTP_ASCII) or die("Can't transfer");
ftp_get($c, $local,  $remote, FTP_ASCII) or die("Can't transfer");

The ftp_put( )function takes a file on your computer and copies it to the remote server; ftp_get( ) copies a file on the remote server to your computer. In the previous code, $remote is the pathname to the remote file, and $local points at the file on your computer.

There are two final parameters passed to these functions. The FTP_ASCII parameter, used here, transfers the file as if it were ASCII text. Under this option, linefeed endings are automatically converted as you move from one operating system to another. The other option is FTP_BINARY, which is used for nonplaintext files, so no linefeed conversions take place.

Use ftp_fget( ) and ftp_fput( ) to download or upload a file to an existing open file pointer (opened using fopen( )) instead of to a location on the filesystem. For example, here's how to retrieve a file and write it to the existing file pointer, $fp:

$fp = fopen($file, 'w');
ftp_fget($c, $fp, $remote, FTP_ASCII)   or die("Can't transfer");

Finally, to disconnect from the remote host, call ftp_close( ) to log out:

ftp_close($c);                          or die("Can't close");

To adjust the amount of seconds the connection takes to time out, use ftp_set_option( ):

// Up the time out value to two minutes:
set_time_limit(120)
$c = ftp_connect('ftp.example.com');
ftp_set_option($c, FTP_TIMEOUT_SEC, 120);

The default value is 90 seconds; however, the default max_execution_time of a PHP script is 30 seconds. So, if your connection times out too early, be sure to check both values.

To use the cURL extension, you must download cURL from http://curl.haxx.se/ and set the --with-curl configuration option when building PHP. To use cURL, start by creating a cURL handle with curl_init(), and then specify what you want to do using curl_setopt(). The curl_setopt( ) function takes three parameters: a cURL resource, the name of a cURL constant to modify, and value to assign to the second parameter. In the Solution, the CURLOPT_FILE constant is used:

$c = curl_init("ftp://$username:$password@ftp.example.com/$remote");
// $local is the location to store file on local client
$fh = fopen($local, 'w') or die($php_errormsg); 
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);

You pass the URL to use to curl_init( ). Because the URL begins with ftp://, cURL knows to use the FTP protocol. Instead of a separate call to log on to the remote server, you embed the username and password directly into the URL. Next, you set the location to store the file on your server. Now you open a file named $local for writing and pass the file handle to curl_setopt( ) as the value for CURLOPT_FILE. When cURL transfers the file, it automatically writes to the file handle. Once everything is configured, you call curl_exec( )to initiate the transaction and then curl_close( ) to close the connection.


PHP Home | All PHP Tutorials | Latest PHP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by David Sklar
Find Difference between two dates in PHP
Reading .CSV file in PHP
Appending One Array to Another in PHP
Removing Duplicate Elements from an Array in PHP
Sorting an Array in PHP
Iterating Through an Array in PHP
Password protecting a page in PHP
Deleting Cookies in PHP
Reading Cookie Values in PHP
Setting cookies in PHP
Encrypting and decrypting in PHP
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Using Text-File Databases in PHP
Upload and Download files with FTP in PHP
Extract files from a .zip file using PHP

More Tutorials in PHP
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Convert XML to CSV in PHP
Password must include both numeric and alphabetic characters - Magento
PHP file upload (Large Files)
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Handling file locks in PHP
HTML table output using Nested for loops in PHP
Count occurrences of a character in a String in PHP

More Latest News
Most Viewed Articles (in PHP )
Exception in module wampmanager.exe at 000F15A0 in Windows 8
isset() function in PHP
Parent: child process exited with status 3221225477 -- Restarting
Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......
Get the next working day in PHP
History and origin of PHP
.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable
Handling BLOB in PHP and MySQL
Reading contents of a File into a String in PHP
Reading word by word from a file in PHP
Reading Cookie Values in PHP
Where does the PHP run?
Function to return number of digits of an integer in PHP
Return multiple values from a function in PHP
Anonymous functions as properties in Classes in PHP
Most Emailed Articles (in PHP)
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Convert XML to CSV in PHP
Using PEAR::Crypt_HMAC in PHP
Password must include both numeric and alphabetic characters - Magento
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Resume or Pause File Uploads in PHP
Comparison operators in PHP
Extract files from a .zip file using PHP
Appending One Array to Another in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
isset() function in PHP
do...while Loops in PHP
Counting Lines, Paragraphs, or Records in a File using pc_split_paragraphs() in PHP