簡體   English   中英

PHP:如何獲取請求頁面並獲取正文和http錯誤代碼

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM