有一个重定向到服务器的信息,一旦响应来自服务器,我想检查HTTP代码,如果有任何代码以4XX开头,则抛出异常.为此我需要知道如何才能从头部获取HTTP代码?此处还涉及到服务器的重定向,所以我害怕卷曲对我没用.
到目前为止,我已经尝试过这个解决方案,但它很慢并且在我的情况下创建脚本超时.我不想增加脚本超时时间并等待更长时间才能获得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;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅:HEAD首先使用PHP Streams,最后它包含示例代码,以及如何执行HEAD请求get_headers.
就像是:
$ch = curl_init();
$httpcode = curl_getinfo ($ch, CURLINFO_HTTP_CODE );
Run Code Online (Sandbox Code Playgroud)
你应该尝试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 ...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11834 次 |
| 最近记录: |