At times the get_file_contents takes too long and that hangs the entire script. Is there any way of setting a time out limit on get_file_contents, without modifying the maximum execution time of the script?
有时get_file_contents需要太长时间并挂起整个脚本。有没有办法在get_file_contents上设置超时限制,而不修改脚本的最大执行时间?
Edit:
Its taking long because the file does not exist. I am getting "failed to open stream: HTTP request failed!" error. But it takes forever.
它花了很长时间,因为文件不存在。我收到“无法打开流:HTTP请求失败!”错误。但它需要永远。
2 个解决方案
#1
36
Seems to be possible in PHP > 5.2.1 by creating a context with the timeout option.
通过使用timeout选项创建上下文,似乎可以在PHP> 5.2.1中实现。
Slightly amended example from the manual page:
手册页中略有修改的示例:
<?php
$opts = array('http' =>
array(
'method' => 'GET',
'timeout' => 120
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/get.php', false, $context);
?>
#2
1
you count use ini_set
and set "default_socket_timeout"
before using file_get_contents
and then restore the old value after it - if would affect some other parts of your code...
你计算使用ini_set并在使用file_get_contents之前设置“default_socket_timeout”然后恢复它之后的旧值 - 如果会影响你代码的其他部分......
#1
36
Seems to be possible in PHP > 5.2.1 by creating a context with the timeout option.
通过使用timeout选项创建上下文,似乎可以在PHP> 5.2.1中实现。
Slightly amended example from the manual page:
手册页中略有修改的示例:
<?php
$opts = array('http' =>
array(
'method' => 'GET',
'timeout' => 120
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/get.php', false, $context);
?>
#2
1
you count use ini_set
and set "default_socket_timeout"
before using file_get_contents
and then restore the old value after it - if would affect some other parts of your code...
你计算使用ini_set并在使用file_get_contents之前设置“default_socket_timeout”然后恢复它之后的旧值 - 如果会影响你代码的其他部分......