我有以下链接:
http://www.compredia.eu/finder_listing.php?cpath=10728,100021,1063355&mode=finder
自动重定向到:
http://www.compredia.eu/hp-printcartridges-for-hp-business-inkjet-2800.html
如何使用curl获取网址的重定向页面?
答案 0 :(得分:1)
这就是我正在使用的东西 - 它也适合你:
<?php
function getRedirectUrl($url){
$redirect_url = null;
$url_parts = @parse_url($url);
if (!$url_parts) return false;
if (!isset($url_parts['host'])) return false; //can't process relative URLs
if (!isset($url_parts['path'])) $url_parts['path'] = '/';
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
if (!$sock) return false;
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = '';
while(!feof($sock)) $response .= fread($sock, 8192);
fclose($sock);
if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
if ( substr($matches[1], 0, 1) == "/" )
return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
else
return trim($matches[1]);
} else {
return false;
}
}
function getAllRedirects($url){
$redirects = array();
while ($newurl = getRedirectUrl($url)){
if (in_array($newurl, $redirects)){
break;
}
$redirects[] = $newurl;
$url = $newurl;
}
return $redirects;
}
function getFinalRedirect($url){
$redirects = getAllRedirects($url);
if (count($redirects)>0){
return array_pop($redirects);
} else {
return $url;
}
}
?>
答案 1 :(得分:0)
$ch = curl_init($url);
//set options
curl_exec($ch);
$lasturl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
答案 2 :(得分:0)
代码:
<?php
function curlRedir($url)
{
$go = curl_init($url);
curl_setopt ($go, CURLOPT_URL, $url);
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++>= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($go, CURLOPT_HEADER, true);
curl_setopt($go, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($go);
$pattern = '/self\.location\.href=\'(.+)\';/';
preg_match($pattern, $data, $matches);
curl_close($go);
return $matches[1];
}
$c = curlRedir("http://www.compredia.eu/finder_listing.php?cpath=10728,100021,1063355&mode=finder");
echo $c;
?>
输出
http://www.compredia.eu/hp-printcartridges-for-hp-business-inkjet-2800.html