bash file_get_contents 返回无法打开流:连接超时错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23487433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:23:26  来源:igfitidea点击:

file_get_contents returns failed to open stream: Connection timed out error

phpbashcurlfile-get-contents

提问by darkraven

I was using the following code on my Centos machine to fetch URL response:

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

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

It returns the error:

它返回错误:

"Warning: file_get_contents(http://www.google.com/): failed to open stream: Connection timed out in testFGC.php on line 3"

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

I've checked the php.inifile. Everything looks fine. iptablesand ip6tablesare off.

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

I've tried using curlinstead of file_get_contents, but that doesn't work as well.

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

But a normal curl on the bash command line works absolutely fine(returns the html content).

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

curl www.google.com

What can be the reason? Can Firewall rules be the problem even though the bash curl is working? Thank you.

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

回答by Karl Schmidt

It seems like its actually a problem with your server, not your code. However, if you say that curl works, you can use curl in your code

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

Hope this helps.

希望这可以帮助。

回答by Jay Patel

The error indicates, that file_get_contentsdoes not get a response from the host www.google.com

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

Otherwise yout code is pefect for getting host content,

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

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

I test on here.... CodeViper

我在这里测试.... CodeViper