方法一:
在php获取http头部信息上,php有个自带的函数get_headers(),我以前也是用这个的,听说效率在win上不咋地,再加上最近研究百度url无果,写了cURL获取重定向url的php代码来折腾。
以前我是用get_headers来获取跳转后的url
1 2 3 4 5 6 7 8 9 10 11 |
//curl的百度百科 $url = 'http://www.baidu.com/link?url=77I2GJqjJ4zBBpC8yDF8xDhiqDSn1JZjFWsHhEoSNd85PkV8Xil-rckpQ8_kjGKNNq'; $header = get_headers($url,1); if (strpos($header[0],'301') || strpos($header[0],'302')) { if(is_array($header['Location'])) { $info = $header['Location'][count($header['Location'])-1]; }else{ $info = $header['Location']; } } echo $info; |
方法二:
CURL是需要设置curl_setopt 和curl_getinfo才可以获取 Location:重定向
1 2 |
//curl的百度百科 $url = 'http://www.baidu.com/link?url=77I2GJqjJ4zBBpC8yDF8xDhiqDSn1JZjFWsHhEoSNd85PkV8Xil-rckpQ8_kjGKNNq'; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$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_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_REFERER, ''); $header = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close($ch); if ($http_code == 301 || $http_code == 302) { preg_match('/Location:(.*?)\n/', $header, $matches); $url = (is_array($matches) && isset($matches[1])) ? trim($matches[1]) : $url; } |
1 |
echo '真实url为:'.$url; |