簡體   English   中英

通過計數避免最長執行時間-PHP

[英]Avoid maximum execution time with a count - PHP

我有一個腳本,基本上是在清理東西。

腳本的一部分需要使用file_get_contents檢查圖像是否存在

知道這會遇到問題,並且會出現Fatal error: Maximum execution time of 30 seconds exceeded並希望避免這種情況。

有沒有一種方法可以設置一個開始計數的計數器,如果在說25秒后file_get_contents失敗,腳本將忽略然后繼續。

我會說,我知道可以,但我不想增加時限。

這是基本腳本:

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

}

除了獲取整個文件外,您還可以使用CURL對它進行“ ping”操作,因此僅獲取其標頭並獲取狀態代碼(200 =文件存在,404 =文件不存在)。

如果文件不是遠程文件,請使用file_exists() 如果file_exists中包含PHP包裝器,這也將很有趣,因此您可以執行以下操作:

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

我不確定這是否可行或是否僅檢查狀態碼,但值得嘗試。

否則,請使用帶有不下載正文的選項的CURL:

curl_setopt($curl, CURLOPT_NOBODY, true);

在CLI中運行此腳本而不是通過瀏覽器運行該腳本,然后將超時設置為2小時並使其運行,這也很好。

如果您無法更改超時,請查看Gearman,然后在使用瀏覽器點擊腳本后簡單地分派工作。

更新

您不必“計數到25”,可以使用以下選項設置此超時:

CURL: http://php.net/manual/en/function.curl-setopt.phpCURLOPT_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不使用。

如果您確實想這樣做,則可以使用php micrtotime或time函數來確定該腳本運行了多長時間(如果需要在25秒后終止該腳本)。 這是它們的文檔條目: http : //php.net/timehttp://php.net/microtime

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM