[英]PHP: How to GET request a page and get body and http error codes
我想知道是否有可能获得HTTP错误代码并在错误而不是false(文件获取内容错误)和错误引发的情况下做出响应。 我在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
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,我想获取错误响应页面。
你应该尝试卷曲
$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);
$context = stream_context_create(array(
'http' => array('ignore_errors' => true),
));
$result = file_get_contents('http://your/url', false, $context);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.