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:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  • PHP 5.5.0 Alpha3 released
  •  

     

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