【问题标题】:Avoid maximum execution time with a count - PHP通过计数避免最大执行时间 - PHP
【发布时间】:2014-02-21 07:46:01
【问题描述】:

我有一个脚本,它基本上是在清理东西。

脚本的一部分需要检查图像是否存在,使用file_get_contents

知道这会遇到问题,我会不时收到Fatal error: Maximum execution time of 30 seconds exceeded 并希望避免这种情况。

有没有办法设置一个开始计数的计数器,如果 file_get_contents 在 25 秒后失败,脚本会忽略然后继续。

我会说,我知道我可以,但我不想增加时间限制。

这是基本脚本:

$query = "select table_id, image_url from table";

$res = $mysqli->query($query) or trigger_error($mysqli->error."[$query]");

while($row = $res->fetch_array()){

    // save the image
    $img = '/path/to/'.$row[table_id].'.jpg';

    //## need to start counting to 25 secs here

    $saveImage = file_put_contents($img, file_get_contents($row[image_ur]));

    //## check if 25 seconds realised, if so with no $saveImage then continue

    if($saveImage){
        // do something else
    }

}

【问题讨论】:

  • 参见:[Timeout a function in PHP][1] [1]: stackoverflow.com/questions/10587323/timeout-a-function-in-php
  • 好吧,如果最大执行时间到期,那么脚本将终止,它不是一个循环,我们可以在 25 秒后刷新页面并使用参数作为最后一个索引重新加载页面,循环可以重新开始索引。对于文件操作,我不确定它是否可以完成,但是您可以增加最大执行时间。
  • 如果您只需要检查图像是否存在,则只需使用 file_exists() 函数而不是 file_get_contents()

标签: php


【解决方案1】:

您可以使用 CURL 来“ping”它而不是获取整个文件,因此您只需获取其标题并获取状态代码(200 = 文件存在,404 = 文件不存在)。

如果文件不是远程文件,请使用file_exists()。 PHP 包装器是否包含在 file_exists 中也会很有趣,因此您可以这样做:

file_exists('http://image.url.com/file.jpg');

我不确定这是否有效或仅检查状态代码,但值得一试。

否则使用 CURL 并选择不下载正文:

curl_setopt($curl, CURLOPT_NOBODY, true);

在 CLI 中而不是通过浏览器运行此脚本也很好,然后将超时设置为 2 小时并让它运行..

如果您无法更改超时,请查看 Gearman,并在使用浏览器点击您的脚本后简单地调度您的作业。

更新

您不必“数到 25”,您可以使用选项设置此超时:

卷曲:http://php.net/manual/en/function.curl-setopt.php - CURLOPT_CONNECTTIMEOUT

string file_get_contents ( string $filename
      [, bool $use_include_path = false
      [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

使用$context:

resource stream_context_create ([ array $options [, array $params ]] )

结合stream_set_timeout:

bool stream_set_timeout ( resource $stream , int $seconds [, int $microseconds = 0 ] )

我强烈建议将 CURL 与 NOBODY 和 TIMEOUT 选项一起使用,这样您的脚本运行速度会快 10 倍并设置超时(25 太多,使用 5 或更低)。

CURL 也使用Keep-Alivefile_get_contents 不使用。

【讨论】:

    【解决方案2】:

    如果你真的想这样做,你可以使用 php 的 micrtotime 或 time 函数来确定脚本运行多长时间,如果你需要在 25 秒后终止脚本。 这是他们的文档条目: http://php.net/timehttp://php.net/microtime

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多