Introduction
In this article I will explain Remote files in PHP. To open or read a file on a remote server and transfer output data you can use the data in a query. First of all enable "allow_url_fopen" in PHP.ini then use HTTP and FTP function URLs with some functions passed as a parameter as a filename. URLs can be used with include(), include_once(), require(), require_once() statements. You can read remote files in one of three ways using PHP.
Example 1
Here you can get the title of a remote page and also write to files on a FTP server using this example:
<?php
$f
=
fopen
("http://www.csharpcorner.com/",
"r");
if
(!$f)
{
echo
"<p>Unable to open remote file";
exit;
}
while
(!feof
($f))
{
$line
=
fgets
($f,
1024);
if
(preg_match
("@\<title\>(.*)\</title\>@i",
$line,
$out))
{
$tpage
=
$out[1];
break;
}
}
fclose($f);
?>
Example 2
You can read the contents of a remote file using this example:
<?php
$f
=
fopen("http://www.csharpcorner.com/",
"rb");
$content = '';
while (!feof($f))
{
$content .= fread($f, 8192);
}
fclose($f);
?>
Example 3
You can sort data on a remote server using the following example:
<?php
$f
=
fopen
("ftp://ftp.csharpcorner.com",
"w");
if
(!$f)
{
echo
"<p>Unable to open remote file for writing.\n";
exit;
}
//Write
the
data
here
fwrite
($f,
$_SERVER['HTTP_USER_AGENT']
.
"\n");
fclose
($f);
?>
Example 4
Another example using fgets() instead of fread():
<?php
if
($f
=
fopen("http://csharpcorner.com",
'r')
{
while(!feof($f))
{
$rd = fgets($f, 1024);
if (eregi("<title>(.*)</title>",
$rd, $output)
{
$tpage = $output[1];
break;
}
}
}
else
echo "Title
of
page
is:
" . $tpage;
fclose($f);
?>