Chapter 19. Using remote files

As long as support for the "URL fopen wrapper" is enabled when you configure PHP (which it is unless you explicitly pass the --disable-url-fopen-wrapper flag to configure), you can use HTTP and FTP URLs with most functions that take a filename as a parameter, including the require() and include() statements.

Note: You can't use remote files in include() and require() statements on Windows.

For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Example 19-1. Getting the title of a remote page

  1 
  2 <?php
  3   $file = fopen("http://www.php.net/", "r");
  4   if (!$file) {
  5     echo "<p>Unable to open remote file.\n";
  6     exit;
  7   }
  8   while (!feof($file)) {
  9     $line = fgets($file, 1024);
 10     /* This only works if the title and its tags are on one line. */
 11     if (eregi("<title>(.*)</title>", $line, $out)) {
 12       $title = $out[1];
 13       break;
 14     }
 15   }
 16   fclose($file);
 17 ?>
 18     

You can also write to files on an FTP as long you connect as a user with the correct access rights, and the file doesn't exist already. To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)

Example 19-2. Storing data on a remote server

  1 
  2 <?php
  3   $file = fopen("ftp://ftp.php.net/incoming/outputfile", "w");
  4   if (!$file) {
  5     echo "<p>Unable to open remote file for writing.\n";
  6     exit;
  7   }
  8   /* Write the data here. */
  9   fputs($file, "$HTTP_USER_AGENT\n");
 10   fclose($file);
 11 ?>
 12     

Note: You might get the idea from the example above to use this technique to write to a remote log, but as mentioned above, you can only write to a new file using the URL fopen() wrappers. To do distributed logging like that, you should take a look at syslog().