【问题标题】:Can I put timeout on PHP for()?我可以在 PHP for() 上设置超时吗?
【发布时间】:2014-05-13 17:12:59
【问题描述】:

如果不可能,我不能让 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,但我不知道如何为整个 curl_multi 请求设置超时。

【问题讨论】:

标签: php loops for-loop timeout limit


【解决方案1】:

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

$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);
}

【讨论】:

  • 为什么要在 for 循环中一次又一次地定义上下文?不能在外面定义一次,在for循环里面使用吗?
  • @hek2mgl 我实际上正在使用 curl_setopt($curly[$id], CURLOPT_TIMEOUT, 1);对于具有 5 个不同 url 请求的 curl_multi。但它最多可以加起来 5 秒。如何为整个 curl_multi 请求设置 1 秒超时?
  • 不幸的是,没有这个选项。让我想一个解决方法..(有趣的问题)
  • 一种解决方法是使用低级套接字通信,您必须自己实现 HTTP。然后就可以使用socket_select()来实现超时了。目前我没有看到更好的解决方案。需要AFK一段时间。如果您有这方面的更新或需要更多帮助,请告诉我
【解决方案2】:
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx); 

Source

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 2011-01-17
    • 2013-08-15
    • 1970-01-01
    • 2011-02-07
    • 2017-09-01
    • 2011-07-20
    • 2010-10-09
    • 1970-01-01
    相关资源
    最近更新 更多