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