【问题标题】:PHP file_get_contents() not workingPHP file_get_contents()不起作用
【发布时间】:2012-08-30 22:07:20
【问题描述】:

谁能解释一下为什么下面的代码会返回警告:

<?php
  echo file_get_contents("http://google.com");
?>

我收到警告:

Warning: file_get_contents(http://google.com): 
failed to open stream: No such file or directory on line 2

见codepad

【问题讨论】:

  • 你在实际服务器上试过了吗?
  • 哦,你的意思是权限问题?
  • @Musa,不,我正在尝试使其基于网络。有解决办法吗?
  • @Vishal,你在键盘上试过了吗?
  • 啊!!只适用于我的本地主机;)

标签: php codepad


【解决方案1】:

作为替代方案,您可以使用 cURL,例如:

$url = "http://www.google.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;

见:cURL

【讨论】:

  • 不错的选择,有时 wamp 服务器不支持“file_get_contents”。
【解决方案2】:

试试这个函数代替 file_get_contents():

<?php

function curl_get_contents($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

它可以像 file_get_contents() 一样使用,但使用 cURL。

在 Ubuntu(或其他具有 aptitude 的类 unix 操作系统)上安装 cURL:

sudo apt-get install php5-curl
sudo /etc/init.d/apache2 restart

另见cURL

【讨论】:

  • 谢谢!它帮助到我! :D 我很感激~ :3
【解决方案3】:

这几乎肯定是由允许 PHP 禁用使用文件处理函数打开 URL 的能力的配置设置引起的。

如果您可以更改 PHP.ini,请尝试打开 allow_url_fopen 设置。另请参阅man page for fopen 了解更多信息(相同的限制会影响所有文件处理功能)

如果您无法打开标记,则需要使用其他方法(例如 Curl)来读取您的 URL。

【讨论】:

  • 好的,所以我尝试在000webhost.com 上运行相同的代码,然后得到“301 已移动”。它启用了allow_url_fopen。有什么想法吗?
  • 如果allow_url_fopen 被禁用,您将不会收到“找不到文件”消息。除此之外,启用设置的键盘帽:codepad.org/dC19DdmI - 问题是未注册 http 流包装器。
【解决方案4】:

如果你运行这段代码:

<?php
    print_r(stream_get_wrappers());
?>

在http://codepad.org/NHMjzO5p 中,您会看到以下数组:

Array
(
    [0] => php
    [1] => file
    [2] => data
)

在 Codepad.Viper 上运行相同的代码 - http://codepad.viper-7.com/lYKihI 您将看到 http 流已启用,因此 file_get_contents 在 codepad.org 中不起作用。

Array 
( 
    [0] => https 
    [1] => ftps 
    [2] => compress.zlib 
    [3] => php 
    [4] => file 
    [5] => glob 
    [6] => data 
    [7] => http 
    [8] => ftp 
    [9] => phar 
)

如果您在 Codepad.Viper 中运行上面的问题代码,那么它会打开 google 页面。 因此,区别在于 http 流在您的 CodePad.org 中被禁用并在 CodePad.Viper 中启用。

要启用它,请阅读以下帖子 How to enable HTTPS stream wrappers。或者使用cURL。

【讨论】:

    【解决方案5】:

    尝试在主机名后面加一个斜杠。

    <?php
        echo file_get_contents("http://google.com/");
    ?>
    

    【讨论】:

      【解决方案6】:

      你可以尝试像这样使用单引号:

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

      【讨论】:

        猜你喜欢
        • 2013-06-30
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 2014-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多