PHP 5.6.0beta1 released

set_time_limit

(PHP 4, PHP 5)

set_time_limitFixe le temps maximum d'exécution d'un script

Description

void set_time_limit ( int $seconds )

Fixe le délai d'expiration d'un script, en secondes. Si cette limite est atteinte, le script s'interrompt, et renvoie une erreur fatale. La valeur par défaut est 30 secondes ou, si c'est le cas, la valeur de la directive max_execution_time définie dans le php.ini.

Lorsqu'elle est appelée, set_time_limit() remet le compteur à zéro. En d'autres termes, si la limite par défaut est à 30 secondes, et qu'après 25 secondes d'exécution du script l'appel set_time_limit(20) est fait, alors le script tournera pendant un total de 45 secondes avant de finir.

Liste de paramètres

seconds

Le temps maximal d'exécution, en secondes. S'il vaut 0, aucune limite n'est imposée.

Valeurs de retour

Aucune valeur n'est retournée.

Notes

Avertissement

Notez que set_time_limit() n'a pas d'effet lorsque PHP fonctionne en mode safe mode. Il n'y a pas d'autre solution que de changer de mode, ou de modifier la durée maximale d'exécution dans le php.ini.

Note:

La fonction set_time_limit() et la directive de configuration max_execution_time n'affectent que le temps d'exécution du script lui-même. Tout temps passé en dehors du script, comme un appel système utilisant system(), des opérations sur les flux, les requêtes sur base de données, etc. n'est pas pris en compte lors du calcul de la durée maximale d'exécution du script. Ceci est faux sous Windows où le temps mesuré est le temps réel.

add a note add a note

User Contributed Notes 22 notes

up
24
eric pecoraro at shepard com
8 years ago
I was having trouble with script timeouts in applications where the user prompted long running background actions. I wrote this cURL/CLI background script that solved the problem when making requests from HTTP.

<?php

/* BACKGROUND CLI 1.0
  
   eric pecoraro _at_ shepard dot com - 2005-06-02
   Use at your own risk. No warranties expressed or implied.

   Include this file at the top of any script to run it in the background
   with no time limitations ... e.g., include('background_cli.php');
  
   The script that calls this file should not return output to the browser.
*/
#  REQUIREMENTS - cURL and CLI
  
if ( !function_exists('curl_setopt') OR !function_exists('curl_setopt')  ) {
      echo
'Requires cURL and CLI installations.' ; exit ;
   }
  
#  BUILD PATHS
  
$script = array_pop(explode('/',$SCRIPT_NAME)) ;
  
$script_dir = substr($SCRIPT_NAME,0,strlen($SCRIPT_NAME)-strlen($script)) ;
  
$scriptURL = 'http://'. $HTTP_HOST . $script_dir . "$script" ;
  
$curlURL = 'http://'. $HTTP_HOST . $script_dir . "$script?runscript=curl" ;

#  Indicate that script is being called by CLI
  
if ( php_sapi_name() == 'cli' ) {
     
$CLI = true ;
   }

#  Action if script is being called by cURL_prompt()
  
if ( $runscript == 'curl' ) {
     
$cmd = "/usr/local/bin/php ".$PATH_TRANSLATED ; // server location of script to run
     
exec($cmd) ;
      exit;
   }

#  USER INTERFACE
   // User answer after submission.
  
if ( $post ) {
     
cURL_prompt($curlURL) ;
      echo
'<div style="margin:25px;"><title>Background CLI</title>';
      echo
'O.K. If all goes well, <b>'.$script.'</b> is working hard in the background with no ' ;
      echo
'timeout limitations. <br><br><form action='.$scriptURL.' method=GET>' ;
      echo
'<input type=submit value=" RESET BACKGROUND CLI "></form></div>' ;
      exit ;
   }
  
// Start screen.
  
if ( !$CLI AND !$runscript ) {
      echo
'<title>Background CLI</title><div style="margin:25px;">' ;
      echo
'<form action='.$scriptURL.' method=POST>' ;
      echo
'Click to run <b>'.$script.'</b> from the PHP CLI command line, in the background.<br><br>' ;
      echo
'<input type=hidden value=1 name=post>' ;
      echo
'<input type=submit value=" RUN IN BACKGROUND "></form></div>' ;
      exit ;
   }

#  cURL URL PROMPT FUNCTION
  
function cURL_prompt($url_path) {
     
ob_start(); // start output buffer
     
$c=curl_init($url_path);
     
curl_setopt($c, CURLOPT_TIMEOUT, 2); // drop connection after 2 seconds
     
curl_exec($c);
     
curl_close($c);
     
ob_end_clean(); // discard output buffer
  
}
?>
up
15
php at mightycpa.com
10 years ago
You may also need to look at Apache's timeout setting (Win32 version for me), I changed max execution time value in php.ini, and still got stopped by Apache's timeout value in the httpd.conf file.
up
9
jonathon dot keogh at gmail dot com
5 years ago
You can do set_time_limit(0); so that the script will run forever - however this is not recommended and your web server might catch you out with an imposed HTTP timeout (usually around 5 minutes).

You should check your web server's guides for more information about HTTP timeouts.

Jonathon
up
8
cweiske at cweiske dot de
5 years ago
To get the currently used time, use getrusage()
up
8
AtlantisNet
5 years ago
In IIS, there is another global timeout setting which will override any PHP settings.  You can alter this timeout by following the following instructions:

http://www.iisadmin.co.uk/?p=7
up
6
mba_aslam at yahoo dot com
7 years ago
while setting the set_time_limit(), the duration of sleep() will be ignored in the execution time. The following illustrates:

<?php

set_time_limit
(20);

while (
$i<=10)
{
        echo
"i=$i ";
       
sleep(100);
       
$i++;
}

?>

Output:
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10
up
0
robertbrogers at gmail dot com
3 months ago
Documentation states:
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

If I have a long running script and i want a exact  time limit, I set this as near as possible to the first line.
up
-1
Silver_Knight
4 years ago
if you are running a script that needs to execute for unknown time, or forever.. you may use
set_time_limit(0);
.....
...
..
.
and at the end of the script use flush() function to tell phpto send out what it has generated.
up
0
rsallo at gna dot NOSPAM dot es
10 years ago
When you are working with IIS, PHP timeout is valid only when it's lower than script timeout defined by IIS.

IIS 5 has a default timeout of 300 seconds. If you need a higher timeout, you also have to change IIS properties. Otherwise, your server will stop your PHP script before it reaches its own timeout.
up
-2
konrads dot smelkovs at gmail dot com
8 years ago
If you are streaming large data from database, it is counted towards the max exec time.
up
-2
rycardo74 at gmail dot com
8 years ago
this work to fine html streaming AND time pass limit

<?php
header
('Content-type: text/plain');
echo
date("H:m:s"), "\n";
set_time_limit(30);
for (
$i = 0; $i < 1000; $i++)
{

    echo
date("H:m:s"),"\n";
    for (
$r = 0; $r < 100000; $r++){
   
$X.=  tan(M_LNPI+log(ceildate("s")*M_PI*M_LNPI+100)));
    }
   
ob_flush();  
   
flush();

}
echo
"work! $x";
?>
up
-5
php at stock-consulting dot com
7 years ago
To find out the currently set time limit, use

<?php
 ini_get
('max_execution_time');
?>

If set_time_limit has been previously called in the script, the result will be the value which was passed to set_time_limit (and not, as the function name "ini_get" appears to suggest, the value from the php.ini file).
up
-11
alexander dot krause at ed-solutions dot de
2 years ago
A nice workaround to have a real max_execution_time (needs posix and pcntl):

<?php
$pid
=pcntl_fork();

if (
$pid) {
 
//long time process
 
$a=0;
  while (
true) {
    echo
"a=$a\n\n";
   
ob_flush();
   
flush();
   
$a++;
   
shell_exec('sleep 10&');
  }
} else {
 
//time-limit checker
 
sleep(5);
 
posix_kill(posix_getppid(),SIGKILL);
}
?>
up
-13
mingalevme at gmail dot com
1 year ago
If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:

<?php

require_once('db.php');

$stmt = $db->query($sql);

while (
$row = $stmt->fetchRow()) {
   
set_time_limit(0);
   
// your code here
}

?>
up
-13
ratty at brohoof dot com
2 years ago
One thing that I wish I had found sooner is, if you're using php-cli and really need to limit the executation time, and if you're in *nix, you can use "timeout" which is part of coreutils.
For example:

timeout 5 /usr/bin/php -q /path/to/script

and it will kill it if it takes longer than 5 seconds.
I had a few quick php scripts I wrote for use with cacti for example.
up
-13
jatin at jatinchimote dot com
8 years ago
If you set the number of seconds to a very large number (not many ppl do that, but just in case) then php exits with a fatal error like :

Fatal error: Maximum execution time of 1 second exceeded in /path/to/your/script/why.php

[EDIT by danbrown AT php DOT net: This is due to the limit of 32-bit signed integers.]
up
-13
bjfieldNO at SPAMgmail dot com
7 years ago
Timeouts after five minutes in IIS on Windows are caused by an inherited CGI Timeout value of 300 seconds.  This is not a PHP problem.  The fix is to add custom values for the files or directories that need longer to run.

In IIS 5.0 or 7.0 (beta as of this note), you can change this value on a fairly granular level using IIS Manager, under (roughly) YOURSITE -> Properties -> Home Directory -> Configuration (button) -> Options, but in IIS 6.0, this functionality is turned off (!), so you have to get into the Metabase.

Find the site number in Metabase Explorer (e.g., 12345678), then from CMD prompt:

[get to the scripts dir]
cd C:\Inetpub\AdminScripts

[this for each subdirectory from off the site root]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY" IIsWebDirectory

[this for the file in question]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php IIsWebFile

[this to set the timeout]
cscript adsutil.vbs set W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php/CGITimeout "7200"

Note:  "7200" is 2 hours in seconds, but can be whatever.

I derived the solution above from this fine article:
http://www.iis-resources.com/modules/AMS/article.php?
storyid=509&page=3
up
-13
Cleverduck
8 years ago
Regarding what 'nytshadow' said, it's important to realize that max-execution-time and the set_time_limit functions measure the time that the CPU is working on the script.  If the script blocks, IE: for input, select, sleep, etc., then the time between blocking and returning is NOT measured.  This is the same when running scripts from the command line interface.  So if you've got a log parser written in PHP that tails a file, that program WILL fail eventually.  It just depends how long it takes to read in enough input to process for 30 seconds.

If you're writing a command line script that should run infinitely, setting max-execution-time to 0 (never stop) is HIGHLY recommended.
up
-15
ravenswd at gmail dot com
4 years ago
Unfortunately, a script which gets into an infinite loop can produce an alarming amount of output in only a few seconds. I was attempting to debug a script, and I added

<?php
set_time_limit
(2);
?>

to the beginning of the script. Unfortunately, even two seconds of run time produced enough output to overload the memory available to my browser.

So, I wrote a short routine which would limit the execution time, and also limit the amount of output returned. I added this to the beginning of my script and it worked perfectly:

<?php
set_time_limit
(2);

ob_start();     // buffer output

function shutdown () {
   
// print only first 2000 characters of output
   
$out = ob_get_clean();
    print
substr($out, 0, 2000);
}

register_shutdown_function('shutdown');
?>
up
-19
BW
4 years ago
If you use Apache you can change maximum execution time by .htaccess with this line

php_value max_execution_time 200
up
-20
agvozden at gmail dot com
3 years ago
If you got something like:

msg: set_time_limit() [function.set-time-limit]: Cannot set time limit in safe mode

try this:

<?php
       
if( !ini_get('safe_mode') ){
           
set_time_limit(25);
        }
?>
up
-37
kamazee at gmail dot com
3 years ago
Keep in mind that for CLI SAPI max_execution_time is hardcoded to 0. So it seems to be changed by ini_set or set_time_limit but it isn't, actually.
The only references I've found to this strange decision are deep in bugtracker (http://bugs.php.net/37306) and in php.ini (comments for 'max_execution_time' directive).
To Top