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.
- <?php
- $myfile = fopen (“http://www.phpzag.com/”, “r”);
- if (!$myfile) {
- echo “<p>Unable to open remote file.\n”;
- exit;
- }
- while (!feof ($myfile)) {
- $data_line = fgets ($myfile, 1024);
- if (preg_match (“@\<title\>(.*)\</title\>@i”, $data_line, $out)) {
- $pagetitle = $out[1];
- break;
- }
- }
- fclose($myfile);
- ?>
In a below example , you can write to remote files on an FTP server .
- <?php
- $myfile = fopen (“ftp://ftp.phpzag.com/data_file”, “w”);
- if (!$myfile) {
- echo “<p>Unable to open remote file for writing.\n”;
- exit;
- }
- fwrite ($myfile, $_SERVER['HTTP_USER_AGENT'] . “\n”);
- fclose ($myfile);
- ?>
Follow @phpzag
