我可以为PHP()提供超时吗?

时间:2014-05-13 17:13:00

标签: php loops for-loop timeout limit

如果不可能,我不能允许file_get_contents工作超过1秒 - 我需要跳到下一个循环。

for ($i = 0; $i <=59; ++$i) {
$f=file_get_contents('http://example.com');

if(timeout<1 sec) - do something and loop next;
else skip file_get_contents(), do semething else, and loop next;
}

是否可以制作这样的功能?

实际上我使用curl_multi并且我无法解释如何在WHOLE curl_multi请求上设置超时。

2 个答案:

答案 0 :(得分:2)

如果您只使用http网址,则可以执行以下操作:

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
    )
));

for ($i = 0; $i <=59; $i++) {
    file_get_contents("http://example.com/", 0, $ctx); 
}

但是,这只是读取超时,即两次读取操作之间的时间(或第一次读取操作之前的时间)。如果下载速率不变,下载速率应该不会出现这种差距,下载可能需要一个小时。

如果您希望整个下载时间不超过一秒,则无法再使用file_get_contents()。我鼓励在这种情况下使用curl。像这样:

// create curl resource
$ch = curl_init();

for($i=0; $i<59; $i++) {

    // set url
    curl_setopt($ch, CURLOPT_URL, "example.com");

    // set timeout
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);

    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string
    $output = curl_exec($ch);

    // close curl resource to free up system resources
    curl_close($ch);
}

答案 1 :(得分:1)

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx); 

Source