【问题标题】:Get the destination URL only without loading the contents with cURL仅获取目标 URL,不使用 cURL 加载内容
【发布时间】:2021-07-28 04:48:32
【问题描述】:

如果我访问网站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 的内容,这会浪费我的带宽和时间。

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

$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);

【问题讨论】:

  • 是什么阻止了您使用curl_setopt($ch, CURLOPT_NOBODY, true); 检索标头?然后,您可以解析 location 标头的标头。
  • 我不知道这存在。谢谢

标签: php curl redirect header


【解决方案1】:

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

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

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

您可以从这些标头中解析 location 部分以获取重定向的 URL。

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

【讨论】:

    猜你喜欢
    • 2011-04-05
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多