flo*_*eft 5 php redirect curl http-status-code-301
我创建了以下PHP函数到网页的HTTP代码.
function get_link_status($url, $timeout = 10)
{
$ch = curl_init();
// set cURL options
$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
CURLOPT_URL => $url, // set URL
CURLOPT_NOBODY => true, // do a HEAD request only
CURLOPT_TIMEOUT => $timeout); // set timeout
curl_setopt_array($ch, $opts);
curl_exec($ch); // do it!
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); // find HTTP status
curl_close($ch); // close handle
return $status;
}
Run Code Online (Sandbox Code Playgroud)
如何修改此功能以遵循301和302重定向(可能的多重定向)并获取最终的HTTP状态代码?
hak*_*kre 17
设置CURLOPT_FOLLOWLOCATION为TRUE.
$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
CURLOPT_URL => $url, // set URL
CURLOPT_NOBODY => true, // do a HEAD request only
CURLOPT_FOLLOWLOCATION => true // follow location headers
CURLOPT_TIMEOUT => $timeout); // set timeout
Run Code Online (Sandbox Code Playgroud)
如果您不必卷曲,您也可以使用标准的PHP http包装器(这可能甚至在内部卷曲).示例代码:
$url = 'http://example.com/';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD"
);
$context = stream_context_create($options);
$body = file_get_contents($url, NULL, $context);
foreach($http_response_header as $header)
{
sscanf($header, 'HTTP/%*d.%*d %d', $code);
}
echo "Status code (after all redirects): $code<br>\n";
Run Code Online (Sandbox Code Playgroud)
一个相关的问题是如何使用PHP检查远程文件是否存在?.
| 归档时间: |
|
| 查看次数: |
8062 次 |
| 最近记录: |