Skip to main content

Read and write to remote files using PHP

PHP strongly allow you to play with remote files. You can easily read content from remote files and also write them. For doing this, you just need to enable  allow_url_fopen in your php.ini file. By enabling it, you can use HTTP and FTP URLs with most of the functions that take a file name as a parameter.  Since  PHP 5.2.0 has enabled allow_url_include in php.ini, the URL can also be used with the include, include_once, require and require_once statements.


For example, you can 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.

In a below example code, we will read file on a remote web server and get the title of page.

 

  1. <?php
  2. $myfile = fopen (“http://www.phpzag.com/”, “r”);
  3. if (!$myfile) {
  4. echo “<p>Unable to open remote file.\n”;
  5. exit;
  6. }
  7. while (!feof ($myfile)) {
  8. $data_line = fgets ($myfile, 1024);
  9. if (preg_match (“@\<title\>(.*)\</title\>@i”, $data_line, $out)) {
  10. $pagetitle = $out[1];
  11. break;
  12. }
  13. }
  14. fclose($myfile);
  15. ?>

In a below example , you can write to remote  files on an FTP server .

  1. <?php
  2. $myfile = fopen (“ftp://ftp.phpzag.com/data_file”, “w”);
  3. if (!$myfile) {
  4. echo “<p>Unable to open remote file for writing.\n”;
  5. exit;
  6. }
  7. fwrite ($myfile, $_SERVER[‘HTTP_USER_AGENT’] . “\n”);
  8. fclose ($myfile);
  9. ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

Shares

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!