使用curl,使用这个:它遵循重定向直到找到端点。在包含的代码中,我使用 goo.gl 将 url 缩短为随机图像。您将看到输出是原始链接(它会输出任意数量的重定向及其 URL),以及最终重定向到实际文件。我想这就是你要找的。我最初并没有写这个,但是前一段时间在某个地方找到了它,并在需要时通过调整再次重复使用了很多次。它似乎很适合许多地方。很高兴把它传下去。我认为这可能有助于实现您正在寻找的东西。
<?php
function follow_redirect($url){
$redirect_url = null;
if(function_exists("curl_init")){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
}
else{
$url_parts = parse_url($url);
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80));
$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 = fread($sock, 2048);
fclose($sock);
}
$header = "Location: ";
$pos = strpos($response, $header);
if($pos === false){
return false;
}
else{
$pos += strlen($header);
$redirect_url = substr($response, $pos, strpos($response, "\r\n", $pos)-$pos);
return $redirect_url;
}
}
$url = 'http://goo.gl/66VJB';
echo '<ol>';
while(($newurl = follow_redirect($url)) !== false){
echo '<li>', $url, '</li>';
$url = $newurl;
}
echo '</ol>';
echo '<a href="', $url, '">', $url, '</a>';
?>
输出:
- http://goo.gl/66VJB
http://1.bp.blogspot.com/_XE0TDW07Noo/TOSVQXZtgAI/AAAAAAAELo/aG80jZ7u_fo/s1600/aptitude_test.gif