【问题标题】:PHP: How to GET request a page and get body and http error codesPHP:如何获取请求页面并获取正文和 http 错误代码
【发布时间】:2019-12-15 03:08:41
【问题描述】:

我想知道是否有可能在错误的情况下获取 HTTP 错误代码和响应,而不是错误(文件获取内容错误)和错误抛出。我在 PHP 7.2 上使用 file_get_contents

我已经尝试过这样做: $r = file_get_contents("https://somewebsite");

输出: PHP Warning: file_get_contents(https://somewebsite): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request 我可以使用 $http_response_header 获取响应代码,但 $r 为 false,我想获取错误响应页面。

【问题讨论】:

  • “错误响应页面”到底是什么意思?
  • 我的意思是页面正文。
  • 是一个 JSON 响应。我确定这是由服务器而不是浏览器生成的。
  • 如果您想更好地控制请求和响应,您可以使用 cURL,或者更好的是使用一些久经考验的 http 库。

标签: php


【解决方案1】:

你应该试试 curl

$ch = curl_init('https://httpstat.us/404');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// if you want to follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// you may want to disable certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode >= 400) {
    // error
    // but $response still contain the response
} else {
    // everything is fine
}

curl_close($ch);

【讨论】:

    【解决方案2】:

    Using file get contents

    $context = stream_context_create(array(
        'http' => array('ignore_errors' => true),
    ));
    
    $result = file_get_contents('http://your/url', false, $context);
    

    【讨论】:

    • 没有必要将此作为答案发布,您只需接受建议的副本即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2015-02-18
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多