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