PHP:限制每个函数的执行时间

标签 php

foreach ($arr as $k => $v)
{
    $r = my_func($v);   

    $new[$k] = $r;
}

如果 my_func() 执行时间超过 10 秒,如何使 $r 返回 false,否则(如果执行时间少于 10 秒) )它将返回 true;

附加信息:my_func() 实际上读取 URL,有时需要很长时间。如果花费的时间超过 10 秒,我希望它返回 false。

最佳答案

您无法通过 PHP 中的函数限制执行时间。但是,不要绝望:如果正如您提到的,您的函数读取 URL,您可以使用 curl扩展名,它具有通过 curl_setopt 设置选项的选项,如下:

CURLOPT_TIMEOUT 允许 cURL 函数执行的最大秒数。 CURLOPT_CONNECTTIMEOUT 尝试连接时等待的秒数。

使用这些,您可以限制使用curl 处理URL 所花费的实际时间。

您还可以使用 http扩展,它还允许您进行 http 连接并具有 timeout options .

最后,您可以使用 context optionsfile_get_contents :

$opts = array('http' =>
    array(
        'timeout' => 1.5 // 1.5 seconds
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/getdata.php', false, $context);

关于PHP:限制每个函数的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9817215/

相关文章:

javascript - 如何在 Cakephp 的模型或 Controller 中调用 javascript 函数?

php - CakePHP 查询后调试之谜

php - 403 Forbidden 如果在 url 中找到单词 "union"

php - 使用 postUpdate($object)/Sonata & Symfony 2 创建对象时写入日志

javascript - PHP 和 AJAX : How can I display json_encode data in PHP while loop?

PHP 向现有数组值添加值

php - IntlDateFormatter::Parse 返回日期解析失败:U_PARSE_ERROR

PHP 分页无法正确运行,在第 6 页停止

php - 避免在 strtotime 为 false 时显示 1970-01-01

java - eclipse : Could not open editor after Eclipse PDT upgrade to version 5. 0.1.201706221952