Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make file_get_contents() return server response despite HTTP errors

If using file_get_contents() to connect to Facebook,

$response = file_get_contents("https://graph.facebook.com/...?access_token=***");
echo "Response: ($response)\n";

And the server returns a non-OK HTTP status, PHP gives a generic error response, and suppresses the response. The body returned is empty.

file_get_contents(...): failed to open stream: HTTP/1.0 400 Bad Request
Response: ()

But if we use cURL, we see that Facebook actually returns a useful response body:

{"error":{"message":"An active access...","type":"OAuthException","code":2500}}

How can I make file_get_contents() return the response body regardless of HTTP errors?

like image 861
forthrin Avatar asked Dec 26 '22 22:12

forthrin


1 Answers

You have to use stream_context_create():

$ctx = stream_context_create(array(
    'http' => array (
        'ignore_errors' => TRUE
     )
));


file_get_contents($url, FALSE, $ctx);
like image 114
hek2mgl Avatar answered Jan 13 '23 19:01

hek2mgl