views:

266

answers:

1

I'm having an odd issue with PHP's file_get_contents.

In the past, file_get_contents on a remote file returns the text of that file regardless of the HTTP status code returned. If I hit an API and it sends back JSON error information with a status of 500, file_get_contents gives me that JSON (with no indication that an error code was encountered).

I've just set up a Ubuntu 10.04 server, which is the first Ubuntu to have PHP 5.3. Instead of giving me the JSON, PHP throws a warning when a 500 error is present. As a result, I can't parse the JSON and give a nice error message.

It's nice that PHP is noticing there's an error in the remote file, but I need the JSON even (especially!) if there's a 500 error. There doesn't appear to be any way to switch this off. Has anyone encountered this? Any tips?

+4  A: 

You can tell PHP to ignore stream errors when using file_get_contents by providing an appropriate stream context (using stream_context_create) with the ignore_errors option set to true.

$context = stream_context_create(array('http'=>array('ignore_errors'=>true)));
$contents = file_get_contents($url, FALSE, $context);

You could also peek at $http_response_header for the response headers, including the status code.

salathe
Cool, thank you!
ceejayoz
Cheers for the `$http_response_header` tip. I can’t believe this isn’t properly documented on php.net!
Mathias Bynens
@Mathias, what would you suggest to improve the documentation? A "see also" link to `$http_response_header`?
salathe
Yeah, something like that. Currently, the *only* reference to `$http_response_header` on the doc page for `file_get_contents` is some guy’s comment. Would be great if you could make it more clear somehow :)
Mathias Bynens
@Mathias, I added a link in the "see also" section of [`file_get_contents`](http://docs.php.net/file_get_contents) to the page describing `$http_response_header`.
salathe
@salathe: In the name of every PHP noob (like me) who visits that page from now on: thank you!
Mathias Bynens
@Mathias, you're welcome. :)
salathe