Read remote file into php
I want to show the contents of a remote file (a file on another server) on my website.
I used the following code, the readfile () function works fine on the current server
<?php
echo readfile("editor.php");
But when I tried to get the deleted file
<?php
echo readfile("http://example.com/php_editor.php");
I got the following error:
301 moved
Document Moved Here 224
I get this error only remote files, local files show up without issue.
Is there a way to fix this?
Thank!
source to share
Option 1 - Curl
Use CURL and set the CURLOPT_FOLLOWLOCATION
-option parameter to true:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http//example.com");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) === FALSE) {
echo "Error: " . curl_error($ch);
} else {
echo curl_exec($ch);
}
curl_close($ch);
?>
Option 2 - file_get_contents
According to PHP documentation file_get_contents () will do up to 20 default redirects. Therefore, you can use this function. On error, file_get_contents () will return FALSE, and otherwise, it will return the entire file.
<?php
$string = file_get_contents("http://www.example.com");
if($string === FALSE) {
echo "Could not read the file.";
} else {
echo $string;
}
?>
source to share