首页 > 解决方案 > 如何使用 PHP 或 cURL 获取真正的最终重定向 URL?

问题描述

我知道CURLINFO_EFFECTIVE_URLofcurl_getinfo()函数可以获得最终的重定向 URL。

但是,当我使用 cURL 尝试像“ http://google.com ”或“ https://en.wikipedia.org/wiki/Redirection ”这样的 URL 并尝试获取时CURLINFO_EFFECTIVE_URL,它仍然返回原始 URL(“ http: //google.com ' 和 ' https://en.wikipedia.org/wiki/Redirection '),而不是真正的重定向 URL(' https://www.google.com ' 或 ' https://en.wikipedia .org/wiki/重定向')。(他们的每个 HTTP 状态码都是 307 和 304)

在浏览器中,如果我输入“ http://google.com ”和“ https://en.wikipedia.org/wiki/Redirection ”,它会自动重定向到“ https://www.google.com ”和' https://en.wikipedia.org/wiki/Redirect '。

为什么CURLINFO_EFFECTIVE_URL不在这里工作?以及如何获得最终重定向的 URL?


编辑

这是我的 cURL 的 PHP 代码:

<?php
$url = "https://en.wikipedia.org/wiki/Redirection";
$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$data = curl_exec($ch);
$redirected_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);

echo $redirected_url;    //It should show the redirected URL.
?>

我使用 5.4.3 作为我的 PHP 版本。有什么不对吗?

标签: phpcurl

解决方案


推荐阅读