如何跟踪URL的重定向

时间:2016-05-29 14:52:43

标签: php redirect

是否可以通过PHP或任何其他网络语言查找网页重定向到的所有网址,最好不仅仅是最终网址,还包括其间的网址。

1 个答案:

答案 0 :(得分:3)

您可以curlcurl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);一起使用以获取几个红色后的最后一个网址,即:

<?php
$ch = curl_init("http://somesite.com/redir1.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);

如果您需要获取每个重定向网址,可以使用:

$httpcode = "301";
$url = "http://somesite.com/redir1.php";
$maxRedir = 1; // avoid endless loop, increase the number bellow to allow more redirs
while(preg_match('/301|302/i', $httpcode) and  $maxRedir <= 4){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $resp = curl_exec($ch);
    $cginfo =  curl_getinfo($ch);
    echo $httpcode =  $cginfo['http_code'];
    preg_match_all('/^Location:(.*)$/mi', $resp, $redir);
    echo "\n" . $url = !empty($redir[1]) ? trim($redir[1][0]) : "";
    echo "\n";
    curl_close($ch);
    $maxRedir++;
}