2009-11-06 57 views
5

我正在使用curl让php向某个网站发送http请求,并将CURLOPT_FOLLOWLOCATION设置为1,以便它遵循重定向。那么,我可以找出它最终重定向的位置吗?找出卷曲被重定向的位置

回答

6

你可以这样做:

curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // returns the last effective URL 
+0

不错。不知道这个。考虑到卷曲选项的数量,它并不总是很容易找到它们。谢谢。 – 2009-11-06 15:21:56

-1

如果您不需要归身,你可以这样来做:

CURLOPT_HEADERCURLOPT_NOBODY。标题“位置”应该被返回并且将包含新的URL。然后根据需要用新的URL执行请求。

2
$ch = curl_init("http://websitethatredirects.com"); 
$curlParams = array(
    CURLOPT_FOLLOWLOCATION => true, 
); 
curl_setopt_array($ch, $curlParams); 
$ret = curl_exec($ch); 
$info = curl_getinfo($ch); 
print $info['url']; 

这会告诉你,你最终被重定向到URL。

0

测试这段代码。它适用于我:

$urls = array(
    'http://www.apple.com/imac', 
    'http://www.google.com/' 
); 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

foreach($urls as $url) { 
    curl_setopt($ch, CURLOPT_URL, $url); 
    $out = curl_exec($ch); 

    // line endings is the wonkiest piece of this whole thing 
    $out = str_replace("\r", "", $out); 

    // only look at the headers 
    $headers_end = strpos($out, "\n\n"); 
    if($headers_end !== false) { 
     $out = substr($out, 0, $headers_end); 
    } 

    $headers = explode("\n", $out); 
    foreach($headers as $header) { 
     if(substr($header, 0, 10) == "Location: ") { 
      $target = substr($header, 10); 

      echo "[$url] redirects to [$target]<br>"; 
      continue 2; 
     } 
    } 

    echo "[$url] does not redirect<br>"; 
}