Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a remote file in php

Tags:

php

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!

like image 841
Amit Verma Avatar asked Jul 22 '15 19:07

Amit Verma


People also ask

How do I read the contents of a file in PHP?

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.

What is the difference between File_get_contents () function and file () function?

file — Reads entire file contents into an array of lines. file_get_contents — Reads entire file contents into a string.

What is remote control PHP?

"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.

When reading and writing files in PHP which function displays the contents of an open file?

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.


1 Answers

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

?>
like image 177
Emil Avatar answered Oct 23 '22 09:10

Emil