【问题标题】:file_get_contents returns failed to open stream: Connection timed out errorfile_get_contents 返回打开流失败:连接超时错误
【发布时间】:2014-06-22 15:18:36
【问题描述】:

我在我的 Centos 机器上使用以下代码来获取 URL 响应:

<?php
ini_set('display_errors', 'On');
$homepage = file_get_contents('http://www.google.com/');
echo $homepage;
?>

返回错误:

“警告:file_get_contents(http://www.google.com/): 无法打开流:第 3 行 testFGC.php 中的连接超时”

我检查了php.ini 文件。一切看起来都很好。 iptablesip6tables 已关闭。

我尝试使用curl 代替file_get_contents,但效果不佳。

但是 bash 命令行上的正常 curl 工作绝对正常(返回 html 内容)。

curl www.google.com

可能是什么原因?即使 bash curl 正在工作,防火墙规则也会成为问题吗?谢谢。

【问题讨论】:

  • 换个网站试试,会成功的..
  • 不适用于任何外部网站。正在为所有本地网络 IP 工作。
  • 您说 curl 不起作用,然后启用 CURLOPT_VERBOSE 并发布 curl 详细日志。 $ch=curl_init();$tmp=tmpfile();curl_setopt_array($ch,array(CURLOPT_VERBOSE=&gt;1,CURLOPT_STDERR=&gt;$tmp,CURLOPT_URL=&gt;'http://google.com'));curl_exec($ch);/*php bug 76268 workaround*/rewind($tmp);var_dump(stream_get_contents($tmp));curl_close($ch);fclose($tmp);,你得到了什么?

标签: php bash curl file-get-contents


【解决方案1】:

这似乎实际上是您的服务器的问题,而不是您的代码。但是,如果您说 curl 有效,则可以在代码中使用 curl

$curl = curl_init('http://www.google.com');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);


$html = curl_exec($curl);
//html var will contain the html code 

if (curl_error($curl)){
    die(curl_error($curl));
}
// Check for HTTP Codes (if you want)
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

curl_close($curl);

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    错误表明,file_get_contents 没有得到主机 www.google.com 的响应

    否则您的代码非常适合获取主机内容,

    <?php
        ini_set('display_errors', 'On');
        $homepage = file_get_contents('http://www.google.com/');
        echo $homepage;
    ?>
    

    我在这里测试.... CodeViper

    【讨论】:

    • 是的,但为什么我没有收到回复?
    • 您是否尝试从其他任何网站获取内容
    • 无法从网络外的任何网站获取任何内容。在本地虚拟机上运行良好
    最近更新 更多