//1、用get_headers函数 php自带的get_headers函数可以获取服务器响应一个HTTP请求所发送的所有标头
function get_redirect_url_by_header($url)
{
$header = get_headers($url, 1);
if (strpos($header[0], '301') !== false || strpos($header[0], '302') !== false) {
if (is_array($header['Location'])) {
return $header['Location'][count($header['Location']) - 1];
} else {
return $header['Location'];
}
} else {
return $url;
}
}
//2、使用cURL函数
function get_redirect_url_by_curl($url, $referer = '', $timeout = 10)
{
$redirect_url = false;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);//不返回请求体内容
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);//允许请求的链接跳转
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: */*', 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)', 'Connection: Keep-Alive'));
if ($referer) curl_setopt($ch, CURLOPT_REFERER, $referer);//设置referer
$content = curl_exec($ch);
if (!curl_errno($ch)) {
$redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);//获取最终请求的url地址
}
return $redirect_url;
}
$headers = get_headers($url, TRUE);
var_dump($headers);