16

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!

Amit Verma
  • 40,709
  • 21
  • 93
  • 115

1 Answers1

22

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;
    }

?>
Emil
  • 1,786
  • 1
  • 17
  • 22
  • It would be good to mention that OP should really check `file_get_contents` result for errors like: `if($string===FALSE) { $string = "Could not load file!"; }` and also do the same for curl's errors. – EdgeCaseBerg Jul 22 '15 at 19:51
  • Thank you! I have added the information in my post. – Emil Jul 22 '15 at 20:03
  • 1
    Don't forget, that for "Option 2" the configuration variable 'allow_url_fopen' must be set to on. – Cuse70 Jan 05 '17 at 18:53