2012-04-19 82 views
113

我正在使用循环中的file_get_contents()方法调用一系列链接。每个链接可能需要超过15分钟才能处理。现在,我担心PHP的file_get_contents()是否有超时期限?file_get_contents()是否有超时设置?

如果是,它将超时通话并移动到下一个链接。我不想在没有事先完成的情况下拨打下一个链接。

那么,请告诉我file_get_contents()是否有超时时间。包含file_get_contents()的文件设置为set_time_limit()为零(无限制)。

+0

交叉参考:您的file_get_contents通话后,从远程服务器检索文件时,[延迟处理PHP](http://stackoverflow.com/q/1605063/367456) – hakre 2014-01-12 09:54:45

+0

我在使用Visual Studio的PHP工具的Visual Studio PHP项目中经历了同样的行为(在同一个“服务器”上查询URL时的超时) Studio扩展。 [更多信息在这里](http://support.devsense.com/viewtopic.php?f=21&t=1916)。 – 2016-10-31 10:24:02

+0

使用[内置PHP服务器查询同一网站上的URL](https://bugs.php.net/bug.php?id=63102)时也会发生这种情况,因为它是单线程的Web服务器。 – 2016-10-31 10:34:36

回答

225

默认超时由default_socket_timeout ini-setting定义,即60秒。你也可以改变它的飞行:

ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes 

另一种方法来设置超时,是使用stream_context_create,设置超时时间在使用HTTP stream wrapperHTTP context options

$ctx = stream_context_create(array('http'=> 
    array(
     'timeout' => 1200, //1200 Seconds is 20 Minutes 
    ) 
)); 

echo file_get_contents('http://example.com/', false, $ctx); 
+6

您可以提供有关如何为https url设置超时的信息吗? – Vinay 2013-05-29 13:35:32

+8

这件事情并不完美,如果你的价值是1200,其实是2400.我只是测试它。 – TomSawyer 2013-10-26 15:46:30

+13

default_socket_timeout,stream_set_timeout和stream_context_create超时都是每行读/写的超时,而不是整个连接超时。 – diyism 2014-11-04 08:27:18

22

由于@diyism “default_socket_timeout,stream_set_timeout和stream_context_create超时都是每行读/写的超时,而不是整个连接超时。”“而@stewe的最高回答使我失败了。

作为使用file_get_contents的替代方法,您总是可以使用curl并且超时。

所以这里有一个工作代码,用于调用链接。

$url='http://example.com/'; 
$ch=curl_init(); 
$timeout=5; 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 

$result=curl_exec($ch); 
curl_close($ch); 
echo $result; 
+1

这个答案给出了另一种控制连接超时的方法(使用'fsockopen'而不是'curl'):http://stackoverflow.com/a/3690321/1869825 – stevo 2015-04-07 19:51:35

+1

你应该在curl中设置CURLOPT_CONNECTTIMEOUT和CURLOPT_TIMEOUT。请参阅http://stackoverflow.com/a/27776164/1863432 – bhelm 2016-05-02 13:36:23

1

,当我在我的主机改变我的php.ini我工作:

; Default timeout for socket based streams (seconds) 
default_socket_timeout = 300 
3

值得注意的是,如果在飞行中改变default_socket_timeout,这可能是恢复它的价值是有用

$default_socket_timeout = ini_get('default_socket_timeout'); 
.... 
ini_set('default_socket_timeout', 10); 
file_get_contents($url); 
... 
ini_set('default_socket_timeout', $default_socket_timeout);