file_get_contents返回打开流失败:连接超时错误


file_get_contents returns failed to open stream: Connection timed out error

我在我的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/):打开流失败:testFGC.php第3行连接超时"

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

我试过使用curl而不是file_get_contents,但这不起作用。

但是bash命令行上的一个普通curl绝对没问题(返回html内容)。

curl www.google.com

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

看起来这实际上是服务器的问题,而不是代码的问题。然而,如果你说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);

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

否则你的代码对于获取主机内容是完美的,

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

我在这里测试.... CodeViper