使用 Curl PHP 获取最终重定向

Get final redirect with Curl PHP

我必须从这里获得最终重定向 url:https://web.archive.org/web/20070701005218/http://www.maladnews.com/ which actually redirects to this: https://web.archive.org/web/20080109064420/http://www.maladnews.com/Site%203/Malad%20City%20&%20Oneida%20County%20News/Malad%20City%20&%20Oneida%20County%20News.html

我尝试了适用于其他网站但不适用于上述网站的其他 Whosebug 答案的答案 link。

我尝试提取常规位置 header:

if(preg_match('#Location: (.*)#', $html, $m))
 $l = trim($m[1]);

并检查了 javascript 方式:

preg_match("/window\.location\.replace\('(.*?)'\)/", $html, $m) ? $m[1] : null;

请帮忙!

根据您的使用情况,将 curl_getinfo()CURLINFO_REDIRECT_URLCURLINFO_EFFECTIVE_URL 结合使用。

CURLINFO_REDIRECT_URL - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL

-- http://php.net/manual/en/function.curl-getinfo.php

示例:

<?php
$url = 'https://google.com/';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$html = curl_exec($ch);

$redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

curl_close($ch);

echo "Original URL:   " . $url . "\n";
echo "Redirected URL: " . $redirectedUrl . "\n";

当我运行这段代码时,输​​出是:

Original URL:   https://google.com/
Redirected URL: https://www.google.com/