Vlada Katlinskaya
Vlada Katlinskaya

Reputation: 1033

Proper way of using file_get_contents() PHP function

I have some troubles with file_get_contents() function: if the remote file redirected to another URI I get script interruption and repetition of script output:

Code:

$context = stream_context_create(['http'=>['timeout'=>10]]);
$url = 'http://example.com/';
echo "URL: $url\n";
$page = file_get_contents($url,FALSE,$context);
echo "Page size: ".strlen($page);

Output:

URL: http://example.com/
URL: http://example.com/

(make note that the output duplicated and there are no "Page size" output)

Expected output:

URL: http://example.com/
Page size: 1000

I believe that file_get_contents() can not handle the redirect that I can see if I'd try my URL in a browser. So I'd like to achieve one of the following:

  1. Catch the error to be able to handle the situation

  2. Load the page despite the redirect

Maybe I can add more options to $context? Or the only way is to move to curl?

Upvotes: 1

Views: 837

Answers (2)

fedeisas
fedeisas

Reputation: 2023

There are many great libraries that abstract curl handling problems from PHP. I personally like Guzzle and Request. You can find links to that libraries here.

That being said, you do have a syntax error in your script, because $context is the third parameter of file_get_content().

It should be:

$page = file_get_contents($url, false, $context);

And you can pass extra options to your stream_context_create. By default it follows redirects, and 20 is the maximum number of redirects before giving up.

Are you sure that URL, when loaded in your browser, doesn't do redirects with JS?

Upvotes: 1

jskidie
jskidie

Reputation: 154

Wrong usage of file_get_contents(): http://php.net/manual/en/function.file-get-contents.php third parameter should be $context

Upvotes: 2

Related Questions