Connecting with FTP Servers

When accessing FTP servers, PHP's stream wrappers come in very handy, as well. You only have read access, but the access is binary-safe nonetheless. This code shows how to download the current README file for Apache from an FTP server and save it to the local hard disk using file_get_contents().


Writing is also possible; just use file_put_contents() or the correct file mode for fopen(). Note, though, that both reading and writing simultaneously is not yet supported.

Reading in an FTP file

  $data =
  file_put_contents('Apache-README.html', $data);
  echo 'File written.';

If you do not provide any credentials, PHP tries to log you in to the FTP server using a guest account most public FTP servers offer. You can, however, also provide the credentials yourself:

$data = file_get_contents

This works for HTTP resources (), too!

PHP also comes with built-in support for FTP and a special set of functions that implement the complete FTP functionality defined in the associated Request for Comment (RFC). In the Windows distributions, this is enabled by default, whereas on other systems, PHP has to be configured with the switch enable-ftp. Then, using the FTP server usually consists of the following steps:

  • Connect to the server using ftp_connect()

  • Log in using ftp_login()

  • Go to the target directory using ftp_chdir()

  • Read a fileftp_get()from or write a fileftp_put()to the FTP server

  • Close the connection using ftp_close()

Because reading probably is more common than writing, the following shows the former task being executed. Again, the Apache README is fetched from an FTP server.

Reading in an FTP file using the built-in functions

  $ftp = @ftp_connect('');
  $login = @ftp_login($ftp, 'anonymous',
  if ($ftp && $login) {
    ftp_chdir($ftp, '/.mnt/0/mirrors/apache/
    ftp_get($ftp, 'Apache-README-ftp.html',
      'README.html', FTP_ASCII);
    echo 'File written.';
  } else {
    echo 'Error!';

Note that the syntax of ftp_get() is a bit strange. After the FTP resource, you have to provide first the local filename, then the remote filename (intuitively, you would expect it to be the other way around). The last parameter is the transfer mode: FTP_ASCII for text files and FTP_BINARY for all other data.

by BrainBellupdated