是否可以通过PHP或任何其他网络语言查找网页重定向到的所有网址,最好不仅仅是最终网址,还包括其间的网址。
答案 0 :(得分:3)
您可以curl与curl_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++;
}