在 PHP 中使用 file_get_contents() 时如何获取重定向后的最终 URL?

Linda Hamilton
发布: 2024-10-28 09:52:29
原创
226 人浏览过

How Can I Get the Final URL After Redirects When Using file_get_contents() in PHP?

File_Get_Contents:揭示最终 URL

问题: 使用 file_get_contents() 抓取内容时,您遇到重定向,但希望发现真实 URL .

解决方案:

虽然 file_get_contents() 通常处理重定向,但如果您明确需要控制,请采用以下方法:

<code class="php">// Disable automatic redirect following
$context = stream_context_create([
    'http' => [
        'follow_location' => false
    ]
]);

// Retrieve the content with no redirects
$html = file_get_contents('http://www.example.com/', false, $context);

// Access the HTTP response headers to determine the actual URL
var_dump($http_response_header);</code>
登录后复制

通过将 'follow_location' 设置为 false,可以防止 file_get_contents() 自动跟踪重定向。响应标头(在 $http_response_header 中提供)将包含“Location”标头,指示任何重定向后的真实 URL。

提示: 此方法的灵感来自于如何做中提供的解决方案我在 PHP 中忽略了带有 file_get_contents 的移动标头?

以上是在 PHP 中使用 file_get_contents() 时如何获取重定向后的最终 URL?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!