如何在PHP中设置get_file_contents的时间限制?

时间:2010-03-13 16:37:09

标签: php

有时get_file_contents需要太长时间并挂起整个脚本。有没有办法在get_file_contents上设置超时限制,而不修改脚本的最大执行时间?

编辑:

它花了很长时间,因为文件不存在。我收到“无法打开流:HTTP请求失败!”错误。但它需要永远。

2 个答案:

答案 0 :(得分:36)

似乎可以在PHP> 5.2.1通过使用timeout option创建上下文。

手册页中略有修改的示例:

<?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);

?>

答案 1 :(得分:1)

您使用ini_set并设置"default_socket_timeout",然后再使用file_get_contents然后恢复之后的旧值 - 如果会影响代码的其他部分...