PHP

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

file_get_contents('ftp://ftp.leo.org/.mnt/0/
mirrors/apache/httpd/README.html')

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

<?php
  $data =
file_get_contents('ftp://ftp.leo.org/.mnt/0/
  mirrors/apache/httpd/README.html');
  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
  ('ftp://USER:PASSWORD@ftp.example.com/');

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

<?php
  $ftp = @ftp_connect('ftp.leo.org');
  $login = @ftp_login($ftp, 'anonymous',
    'email@example.com');
  if ($ftp && $login) {
    ftp_chdir($ftp, '/.mnt/0/mirrors/apache/
      httpd/');
    ftp_get($ftp, 'Apache-README-ftp.html',
      'README.html', FTP_ASCII);
    echo 'File written.';
    ftp_close($ftp);
  } 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
Advertisement: