仅获取目标 URL 而无需使用 cURL 加载内容

Get the destination URL only without loading the contents with cURL

如果我访问网站 https://example.com/a/abc?name=jack,我将被重定向到 https://example.com/b/uuid-123。我只想要结尾 URL,即 https://example.com/b/uuid-123https://example.com/b/uuid-123 的内容大约有 1mb,但我对内容不感兴趣。我只想要重定向的 URL 而不是内容。我怎样才能获得重定向的 URL 而不必加载 1mb 的内容,这会浪费我的带宽和时间。

我在 Whosebug 上看到了一些关于重定向的问题,但没有看到关于如何不加载内容的问题。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/a/abc?name=jack');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$end_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);

echo('End URL is ' . $end_url);

为了清楚起见,我也将其添加为答案。

您可以通过将 CURLOPT_NOBODY 设置为 true 来告诉 curl 仅检索 headers。

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);

从这些 headers 您可以解析 location 部分以获得重定向的 URL.

为潜在的未来读者编辑:CURLOPT_HEADER 也需要设置为 true,我已将其省略,因为您已经将其包含在代码中。