找出卷曲重定向的位置

时间:2009-11-06 14:59:52

标签: php http curl libcurl

我正在使用curl让php向某个网站发送一个http请求并将CURLOPT_FOLLOWLOCATION设置为1,以便它跟随重定向。那怎么样,我能找到它最终重定向的位置吗?

4 个答案:

答案 0 :(得分:6)

您可以执行以下操作:

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

答案 1 :(得分: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'];

这将显示您最终重定向到的网址。

答案 2 :(得分: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>";
}

答案 3 :(得分:-1)

如果你不需要最终的身体,你可以这样做:

设置CURLOPT_HEADERCURLOPT_NOBODY。应返回标题“Location”并包含新的url。然后在必要时使用新网址执行请求。