使file_get_contents()不顾HTTP错误返回服务器响应


Make file_get_contents() return server response despite HTTP errors

如果使用file_get_contents()连接到Facebook,

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

服务器返回一个非OK HTTP状态,PHP给出一个通用的错误响应,并抑制该响应。返回的正文为空。

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

但如果我们使用cURL,我们会看到Facebook实际上返回了一个有用的响应体:

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

如何使file_get_contents()返回响应正文而不管HTTP错误?

您必须使用stream_context_create():

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

file_get_contents($url, FALSE, $ctx);

您可以忽略file_get_contents抛出的错误

$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);