yarek
yarek

Reputation: 12044

How to stop a php script after N seconds using set_time_limit?

I have that simplest possible script:

 <?php
if( ini_get('safe_mode') ){
  echo "safe mode !";
}else{
   echo "NOT safe mode !";
}

set_time_limit(3);

for ($i=0;$i<30;$i++) {
    sleep(1);
    echo $i;
}

I have as output Not safe mode 0123456....

Why does my script does not stop after 3 seconds ?

(I run it in SSH console)

Upvotes: 1

Views: 1876

Answers (2)

ChristianF
ChristianF

Reputation: 2061

AS @iainn said in his answer, set_time_limit() only counts the actual processing time the PHP script does. So when sleeping or waiting for other processes, it won't be counted towards the limit. (Except for on Windows.)

However, to answer the question in your title:
In order to stop it after 3 seconds of "real time", simply create a variable that contains the starting time (in ms), and then check this inside the loop. Preferably before the sleep. Then, if it's > 3000 ms just break from the loop. ;)

Upvotes: 0

iainn
iainn

Reputation: 17417

Time spent sleeping doesn't count towards script execution time. From the manual:

The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

Upvotes: 2

Related Questions