PHP ini file_get_contents外部URL

问题描述 投票:38回答:7

我使用以下PHP函数:

file_get_contents('http://example.com');

每当我在某个服务器上执行此操作时,结果为空。当我在其他任何地方进行此操作时,结果就是页面的内容可能是什么。但是,当我在结果为空的服务器上,在本地使用该函数 - 无需访问外部URL(file_get_contents('../simple/internal/path.html');),它确实有效。

现在,我很确定它与某个php.ini配置有关。我不确定的是哪一个。请帮忙。

php url external file-get-contents ini
7个回答
40
投票

您正在寻找的设置是allow_url_fopen

你有两种方法绕过它而不改变php.ini,其中一种是使用fsockopen(),另一种是使用cURL

我推荐使用cURL而不是file_get_contents(),因为它是为此而构建的。


31
投票

作为Aillyn答案的补充,您可以使用类似下面的函数来模拟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');

4
投票

这与ini配置设置allow_url_fopen有关。

您应该知道启用该选项可能会使代码中的某些错误被利用。

例如,验证输入失败可能会变成一个成熟的远程执行代码漏洞:

copy($_GET["file"], "."); 

4
投票
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

最适合http url,但如何打开https url帮助我


2
投票

上面提供的答案解决了问题,但没有解释OP描述的奇怪行为。这个解释应该有助于测试开发环境中站点之间的通信,这些站点都位于同一主机上(和相同的虚拟主机;我正在使用apache 2.4和php7.0)。

我遇到的file_get_contents()有一个微妙的地方,这绝对是相关的,但没有得到解决(可能因为它几乎没有记录或没有记录我可以告诉或记录在一个我无法找到的模糊的PHP安全模型白皮书)。

随着allow_url_fopen在所有相关背景中设置为Off(例如/etc/php/7.0/apache2/php.ini/etc/php/7.0/fpm/php.ini等等)和allow_url_fopen在命令行上下文中设置为On(即/etc/php/7.0/cli/php.ini),将允许调用file_get_contents()获取本地资源,并且不会发出警告记录如下:

file_get_contents('php://input');

要么

// Path outside document root that webserver user agent has permission to read. e.g. for an apache2 webserver this user agent might be www-data so a file at /etc/php/7.0/filetoaccess would be successfully read if www-data had permission to read this file
file_get_contents('<file path to file on local machine user agent can access>');

要么

// Relative path in same document root
file_get_contents('data/filename.dat')

总之,限制allow_url_fopen = Off类似于iptables链中的OUTPUT规则,其中限制仅在尝试“退出系统”或“改变上下文”时应用。

注: allow_url_fopen在命令行上下文中设置为On(即/etc/php/7.0/cli/php.ini)就是我在我的系统上所拥有的但是我怀疑它与我提供的解释没有关系,即使它被设置为Off,除非你当然通过运行你的测试来测试来自命令行本身的脚本。我没有在命令行上下文中将allow_url_fopen设置为Off来测试行为。


1
投票

这也将为外部链接提供绝对路径,而无需使用php.ini

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.your_external_website.com/$2$3', $result);
echo $result
?>

0
投票

加:

allow_url_fopen=1

在你的php.ini文件中。如果您使用共享主机,请先创建一个。

© www.soinside.com 2019 - 2024. All rights reserved.