I want to show contents of a remote file (a file on another server) on my website.
I used the following code, readfile() function is working fine on the current server
<?php
echo readfile("editor.php");
But when I tried to get a remote file
<?php
echo readfile("http://example.com/php_editor.php");
It showed the following error :
301 moved
The document has moved here 224
I am getting this error remote files only, local files are showing with no problem.
Is there anyway to fix this?
Thanks!
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
file — Reads entire file contents into an array of lines. file_get_contents — Reads entire file contents into a string.
"Remote Control" is a PHP class library that allows you to programically control a remote device via its CLI interface (usually via SSH or Telnet) or any other command via STDIN and STDOUT using Expect in an easy to use object oriented manner.
PHP Read File - fread() The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
Option 1 - Curl
Use CURL and set the CURLOPT_FOLLOWLOCATION
-option 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 the PHP Documentation file_get_contents() will follow up to 20 redirects as default. Therefore you could use that function. On failure, 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;
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With