当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

You have to use stream_context_create():

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


file_get_contents($url, FALSE, $ctx);
网友答案:

You could ignore the errors file_get_contents throws

$opts = array(
  'http'=>array(
    'ignore_errors'=> true,
  )
);

$context = stream_context_create($opts);
$file = file_get_contents('https://graph.facebook.com/...?access_token=***', false, $context);

var_dump($file);
分享给朋友:
您可能感兴趣的文章:
随机阅读: