Reading a Remote file using PHP
There are several way to read a remote file from php but we will discuss 3 ways:
1.fopen
2.
Use file_get_contents()
2. CURL
1 . Using fopen()
If you use fopen() to read a remote file the process is as simple as reading from a local file. The only difference is that you will specify the URL instead of the file name. Take a look at the example below :
$file = fopen ( "http://www.google.com" , "r" );
$site = fread ( $file , 200000 );
fclose ( $file );
print $site ;
?>
2. Using file_get_contents()
This is very simple way to reading a remote file. Just call this function and specify a url as the parameter. But make sure you remember to check the return value first to determine if it return an error before processing the result
if ($content !== false) {
echo $content
} else {
echo "Invalid URL"
}
3. CURL
The function needs to be called by providing the URL for the resource you need and it will retrieve the resource's content.
Example of usage :
and the function itself :
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$tmp = curl_exec($ch);
curl_close($ch);
if ($tmp != false){
return $tmp;
}