Read and write to remote files using PHP

January 31st, 2013 by Laeeq | No comments

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

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • How to Remove Leading & Trailing White Spaces with PHP
  • Parse HTML/Web Pages with PHP
  • Block Multiple IP Addresses Using PHP
  • How much memory do PHP variables use?
  • Manipulating PHP arrays: push, pop, shift, unshift
  •  

     

    1. No comments yet.
    1. No trackbacks yet.