首页 >后端开发 >php教程 >为什么 PHP 的 `file_get_contents` 无法获取外部 URL,如何修复?

为什么 PHP 的 `file_get_contents` 无法获取外部 URL,如何修复?

Barbara Streisand
Barbara Streisand原创
2024-12-24 20:07:12833浏览

Why Does PHP's `file_get_contents` Fail to Fetch External URLs, and How Can I Fix It?

PHP file_get_contents 无法获取外部 URL 内容

尝试使用 PHP file_get_contents 函数检索远程 URL 的内容时(例如、 file_get_contents('http://example.com')),您会遇到结果为在特定服务器上始终为空。但是,使用相同的函数访问本地文件会返回预期结果。

php.ini 中的可能原因

空结果可能归因于 PHP 中的配置设置php.ini 文件。

解决方案

至要解决此问题,请检查 php.ini 文件中的以下特定配置:

  • allow_url_fopen:确保启用此设置(设置为 1 或打开)。它控制 PHP 是否可以使用文件系统函数访问 URL。
  • allow_url_include:如果您想阻止 PHP 直接包含远程 URL,请禁用此设置(设置为 0 或关闭)。
  • file_get_contents.allow_url_fopen:如果存在,此设置将覆盖allow_url_fopen 专门用于 file_get_contents。确保已启用(设置为 1)。

如果这些设置未按描述设置,请相应地调整它们并重新启动 PHP 服务器以应用更改。

替代方法

如果您无法修改 php.ini 设置或更喜欢不同的方法,您可以模仿使用 cURL 获取 file_get_contents,如下例所示:

function get_content($URL){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $URL);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

echo get_content('http://example.com');

以上是为什么 PHP 的 `file_get_contents` 无法获取外部 URL,如何修复?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn