downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

sys_get_temp_dir> <set_magic_quotes_runtime
Last updated: Fri, 13 Nov 2009

view this page in

set_time_limit

(PHP 4, PHP 5)

set_time_limitLimita o tempo de execução do script

Descrição

void set_time_limit ( int $seconds )

Define o número de segundos durante os quais é permitido a execução do script. Se este limite é atingido, o script retorna um erro fatal. O limite padrão é de 30 segundos, ou se existir o valor definido o valor max_execution_time definido no php.ini. Se seconds for definido como zero, não é imposto nenhum limite.

Quando utilizada, set_time_limit() reinicia o contador do limite do tempo a partir de zero. Em outras palavras, se o limite for 30 segundos, e 25 segundos depois do inicio da execução do script for utilizada a função com por exemplo, set_time_limit(20), o script será executado por 45 segundos até acabar o tempo.

Aviso

set_time_limit() não tem efeito quando o PHP esta sendo executado em safe mode. Não existe como contornar sem desabilitar o safe mode ou mudar o limite de tempo no php.ini.

Nota: A função set_time_limit() e a diretiva de configuração max_execution_time somente afetam a execução do script em si mesmo. Qualquer tempo gasto com atividades que aconteçam fora da execução do script como chamadas de sistema usando system(), operações de streams, consultas em banco de dados, etc. não é incluso ao determinar o limite de tempo que o script esta sendo executado.

Veja também: max_execution_time e max_input_time.



sys_get_temp_dir> <set_magic_quotes_runtime
Last updated: Fri, 13 Nov 2009
 
add a note add a note User Contributed Notes
set_time_limit
ravenswd at gmail dot com
15-Aug-2009 11:46
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');
?>
BW
17-May-2009 12:08
If you use Apache you can change maximum execution time by .htaccess with this line

php_value max_execution_time 200
cweiske at cweiske dot de
02-Sep-2008 11:38
To get the currently used time, use getrusage()
jonathon dot keogh at gmail dot com
18-Jul-2008 09:07
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
gib at pganet dot com
20-Jun-2008 07:25
if you are using win2008server, iis7, then before using this option, do not forget to set some variables.

at:

%windir%\system32\inetsrv\

directory, execute the following commands to set the max time to 300 sec. (replace the PHPDIR and PHPEXE with the real ones):

appcmd set config /section:system.webServer/fastCGI /[fullPath='PHPDIR\PHPEXE'].activityTimeout:300
appcmd set config /section:system.webServer/fastCGI /[fullPath='PHPDIR\PHPEXE'].requestTimeout:300

If you want to make double-check that the configuration worked properly, you can check it like this:

appcmd list config -section:system.webServer/fastCgi
AtlantisNet
04-Jun-2008 07:08
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
riki1512
05-Jun-2007 12:29
Please note that, under Linux, sleeping time is ignored, but under Windows, it counts as execution time.
php at stock-consulting dot com
12-Jan-2007 01:30
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).
bjfieldNO at SPAMgmail dot com
10-Jan-2007 10:53
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
mba_aslam at yahoo dot com
05-Jan-2007 01:50
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
27-Sep-2006 09:03
After the error

Fatal error: Maximum execution time of [...] seconds exceeded [...]

has appeared, shut-down functions are still called (afterwards). So, by using register_shutdown_function, you can save data in a session and offer the user a link to start the script again. Then the script can go on with the Session-data.

Example: if you are analyzing a text-file, you can save your analyzed data in a session together with the position of the filepointer (ftell) and start from that possition the next time the user runs the script (fseek).

To determine whether the script was finished or aborted, you simply set a bool false at the beginning and true at the end, and in the shutdown-function you check if it's still false.
konrads dot smelkovs at gmail dot com
01-Apr-2006 02:35
If you are streaming large data from database, it is counted towards the max exec time.
jatin at jatinchimote dot com
02-Mar-2006 06:54
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.]
Cleverduck
28-Feb-2006 09:36
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.
rycardo74 at gmail dot com
25-Nov-2005 06:52
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";
?>
nytshadow
14-Jul-2005 03:15
This tripped me up for a bit until I read through the ini settings.  When doing file uploads, max_execution_time does not affect the time even though the error message indicates the script has exceeded the maximum execution time.  The max_input_time determines how much time PHP will wait to receive file data.  The default setting is 60 seconds so while I had my max_execution_time set to 300, the script would fail after 60 seconds but report that it had exceeded the max execution time of 300.
Sjoerd van der Hoorn
21-Jun-2005 10:08
When using the set_time_limit() function, the browser will stop after about 30 seconds if it does not get new data. To prevent this, you can send every 10 seconds a little snippet of data (like a single character) to the browser. The code below is tested with both Internet Explorer and Firefox, so it will stay online all the time.

You should also create a file called chatdata.txt which contains the last thing said on a chatbox. Please note that you can also replace this function with a MySQL or other database function...

<?php

set_time_limit
(900);

// Start output buffering
ob_start();

$message = "First test message";
$oldmessage = "bla";

// Keep on repeating this to prevent PHP from stopping the script
while (true)
{
   
$timeoutcounter = 0;
    while (
$message == $oldmessage)
    {
       
// If 10 seconds elapsed, send a dot (or any other character)
       
if ($timeoutcounter == 10)
        {
            echo
".";
           
flush();
           
ob_flush();
           
$timeoutcounter = 0;
        }
       
// Timeout executing
       
sleep(1);
       
// Check for a new message
       
$message = file_get_contents("chatdata.txt");
       
$timeoutcounter++;
    }

   
// Keep the old message in mind
   
$oldmessage = $message;

   
// And send the message to the user
   
echo "<script>window.alert(\"" . $message . "\");</script>";

   
// Now, clear the output buffer
   
flush();
   
ob_flush();
}

?>
eric pecoraro at shepard com
06-Jun-2005 07:57
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
  
}
?>
php at mightycpa.com
26-Jun-2003 08:30
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.
rsallo at gna dot NOSPAM dot es
30-May-2003 11:28
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.

sys_get_temp_dir> <set_magic_quotes_runtime
Last updated: Fri, 13 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites