O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.6. Getting and Putting Files with FTP

Problem

You want to transfer files using FTP.

Solution

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);

Discussion

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required