[英]HTTP response code after redirect
有一個重定向到服務器的信息,一旦服務器發出響應,我想檢查HTTP代碼是否拋出異常,如果有任何以4XX開頭的代碼。 為此,我需要知道如何僅從標頭中獲取HTTP代碼? 另外,這里涉及到服務器的重定向,所以我擔心curl對我沒有用。
到目前為止,我已經嘗試過該解決方案,但是它很慢,並且在我的情況下會導致腳本超時。 我不想增加腳本超時時間,而只是為了獲取HTTP代碼而等待更長的時間。
預先感謝您的任何建議。
使用get_headers
並請求第一響應行的方法將返回重定向的狀態代碼(如果有) ,更重要的是,它將執行GET請求,該請求將傳輸整個文件。
您只需要一個HEAD請求,然后解析頭並返回最后的狀態碼。 以下是執行此操作的代碼示例,它使用$http_response_header
而不是get_headers
,但是數組的格式相同:
$url = 'http://example.com/';
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
);
$context = stream_context_create($options);
$body = file_get_contents($url, NULL, $context);
$responses = parse_http_response_header($http_response_header);
$code = $responses[0]['status']['code']; // last status code
echo "Status code (after all redirects): $code<br>\n";
$number = count($responses);
$redirects = $number - 1;
echo "Number of responses: $number ($redirects Redirect(s))<br>\n";
if ($redirects)
{
$from = $url;
foreach (array_reverse($responses) as $response)
{
if (!isset($response['fields']['LOCATION']))
break;
$location = $response['fields']['LOCATION'];
$code = $response['status']['code'];
echo " * $from -- $code --> $location<br>\n";
$from = $location;
}
echo "<br>\n";
}
/**
* parse_http_response_header
*
* @param array $headers as in $http_response_header
* @return array status and headers grouped by response, last first
*/
function parse_http_response_header(array $headers)
{
$responses = array();
$buffer = NULL;
foreach ($headers as $header)
{
if ('HTTP/' === substr($header, 0, 5))
{
// add buffer on top of all responses
if ($buffer) array_unshift($responses, $buffer);
$buffer = array();
list($version, $code, $phrase) = explode(' ', $header, 3) + array('', FALSE, '');
$buffer['status'] = array(
'line' => $header,
'version' => $version,
'code' => (int) $code,
'phrase' => $phrase
);
$fields = &$buffer['fields'];
$fields = array();
continue;
}
list($name, $value) = explode(': ', $header, 2) + array('', '');
// header-names are case insensitive
$name = strtoupper($name);
// values of multiple fields with the same name are normalized into
// a comma separated list (HTTP/1.0+1.1)
if (isset($fields[$name]))
{
$value = $fields[$name].','.$value;
}
$fields[$name] = $value;
}
unset($fields); // remove reference
array_unshift($responses, $buffer);
return $responses;
}
有關更多信息,請參見: HEAD首先使用PHP Streams ,最后包含示例代碼,以及如何使用get_headers
進行HEAD請求。
就像是:
$ch = curl_init();
$httpcode = curl_getinfo ($ch, CURLINFO_HTTP_CODE );
您應該嘗試HttpEngine類。 希望這可以幫助。
-
編輯
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $your_agent_variable);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $your_referer);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode ...)
您找到的解決方案看起來不錯。 如果服務器無法及時向您發送http標頭,則問題在於另一台服務器已損壞或負載很重。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.