How do i increase php time limit?

What Is The PHP Time Limit?

The PHP Time Limit is the amount of time that your site will spend on a single operation before timing out. PHP will timeout and exit with the following error once it reaches the maximum allowed time for it to execute your scripts;

Fatal error: Maximum execution time of 30 seconds exceeded in yourscript.php

You can avoid this error by increasing the maximum execution time for PHP. This can be set globally or from within your PHP scripts via any of these options;

1. Contact Your Host

Increasing the PHP Time Limit is complex and the process that differs from hosts to hosts. So it is always better to get it done from someone who knows it well. So just get in touch with your hosting company and they will be happy to do it for you.

2. Configuring php.ini

PHP time limit can be configured in php.ini, open it up and change the following line to something more suitable:

max_execution_time = 300

NOTE: PHP time limit is measured in seconds!

In order to enable PHP time limit, Apache needs to be restarted after php.ini has been edited.

3. Setting PHP time limit within wp-config.php

This is basically the same as the previous solution, but it’s actually a function that you call from your PHP script. It’s a general function to override any configuration options set in your PHP‘s configuration file and will only affect the execution of the scripts that call the function.

When placed at the start of your PHP script, the following function call will allow it to run for 300 seconds (5 minutes).

set_time_limit(300);

4. Modifying the .htaccess file

Some of you might have the .htaccess file where you can simply add / edit this line of code to increase the time limit.

max_execution 300

Create stunning Blog for just $59

Buy now

(PHP 4, PHP 5, PHP 7, PHP 8)

set_time_limitLimits the maximum execution time

Description

set_time_limit(int $seconds): bool

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.

Parameters

seconds

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

Return Values

Returns true on success, or false on failure.

Notes

Note:

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.

kexianbin at diyism dot com

8 years ago

Both set_time_limit(...) and  ini_set('max_execution_time',...); won't count the time cost of sleep,file_get_contents,shell_exec,mysql_query etc, so i build this function my_background_exec(), to run static method/function in background/detached process and time is out kill it:

my_exec.php:
function my_background_exec($function_name, $params, $str_requires, $timeout=600)
         {
$map=array('"'=>'\"', '$'=>'\$', '`'=>'\`', '\\'=>'\\\\', '!'=>'\!');
         
$str_requires=strtr($str_requires, $map);
         
$path_run=dirname($_SERVER['SCRIPT_FILENAME']);
         
$my_target_exec="/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} \\\$params=json_decode(file_get_contents('php://stdin'),true);call_user_func_array('{$function_name}', \\\$params);\"";
         
$my_target_exec=strtr(strtr($my_target_exec, $map), $map);
         
$my_background_exec="(/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} my_timeout_exec(\\\"{$my_target_exec}\\\", file_get_contents('php://stdin'), {$timeout});\" <&3 &) 3<&0";//php by default use "sh", and "sh" don't support "<&0"
         
my_timeout_exec($my_background_exec, json_encode($params), 2);
         }

function

my_timeout_exec($cmd, $stdin='', $timeout)
         {
$start=time();
         
$stdout='';
         
$stderr='';
         
//file_put_contents('debug.txt', time().':cmd:'.$cmd."\n", FILE_APPEND);
          //file_put_contents('debug.txt', time().':stdin:'.$stdin."\n", FILE_APPEND);
$process=proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
          if (!
is_resource($process))
             {return array(
'return'=>'1', 'stdout'=>$stdout, 'stderr'=>$stderr);
             }
         
$status=proc_get_status($process);
         
posix_setpgid($status['pid'], $status['pid']);    //seperate pgid(process group id) from parent's pgidstream_set_blocking($pipes[0], 0);
         
stream_set_blocking($pipes[1], 0);
         
stream_set_blocking($pipes[2], 0);
         
fwrite($pipes[0], $stdin);
         
fclose($pipes[0]);

          while (

1)
                {
$stdout.=stream_get_contents($pipes[1]);
                
$stderr.=stream_get_contents($pipes[2]);

                 if (

time()-$start>$timeout)
                    {
//proc_terminate($process, 9);    //only terminate subprocess, won't terminate sub-subprocess
                    
posix_kill(-$status['pid'], 9);    //sends SIGKILL to all processes inside group(negative means GPID, all subprocesses share the top process group, except nested my_timeout_exec)
                     //file_put_contents('debug.txt', time().":kill group {$status['pid']}\n", FILE_APPEND);
                    
return array('return'=>'1', 'stdout'=>$stdout, 'stderr'=>$stderr);
                    }
$status=proc_get_status($process);
                
//file_put_contents('debug.txt', time().':status:'.var_export($status, true)."\n";
                
if (!$status['running'])
                    {
fclose($pipes[1]);
                    
fclose($pipes[2]);
                    
proc_close($process);
                     return
$status['exitcode'];
                    }
usleep(100000);
                }
         }
?>

a_class.php:
class A
{
    static function
jack($a, $b)
           {
sleep(4);
           
file_put_contents('debug.txt', time().":A::jack:".$a.' '.$b."\n", FILE_APPEND);
           
sleep(15);
           }
}
?>

test.php:
require 'my_exec.php';my_background_exec('A::jack', array('hello', 'jack'), 'require "my_exec.php";require "a_class.php";', 8);
?>

mba_aslam at yahoo dot com

15 years ago

while setting the set_time_limit(), the duration of sleep() will be ignored in the execution time. The following illustrates:

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

jonathon dot keogh at gmail dot com

14 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

eric pecoraro at shepard com

17 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.

/* 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
'
Background CLI';
      echo
'O.K. If all goes well, '.$script.' is working hard in the background with no ' ;
      echo
'timeout limitations.

' ;
      echo
'
'
;
      exit ;
   }
  
// Start screen.
  
if ( !$CLI AND !$runscript ) {
      echo
'Background CLI
' ;
      echo
'
' ;
      echo
'Click to run '.$script.' from the PHP CLI command line, in the background.

' ;
      echo
'' ;
      echo
'
'
;
      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
  
}
?>

Anonymous

2 years ago

if you want to check how much time remains, this should work (at least on Windows, on non-Windows platforms, i'm not sure)

$seconds_remaining_until_termination = ini_get('max_execution_time') === "0" ? null : ((int)ini_get('max_execution_time'))-(microtime(true)-$_SERVER['REQUEST_TIME_FLOAT']);

gives you number of seconds until the script will be terminated due to the time limit. (tested on Windows 7 X64 SP1 with PHP 7.3.7)  - or gives you null if there is no time limit.

robertbrogers at gmail dot com

8 years 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.

php at mightycpa.com

19 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.

f.nakamura

7 years ago

set_tme_limit resets the execution time count.

test code1:
echo '';
set_time_limit(1);
$i = 0;
while(++
$i < 100000001){
        if(
$i % 100000 == 0){
                echo
$i / 100000, "
\n"
;
        }
}
echo
"done.
\n"
;// will not echo 'done.'.
?>

test code2:
echo '';
set_time_limit(1);
$i = 0;
while(++
$i < 100000001){
        if(
$i % 100000 == 0){
               
set_time_limit(1);
                echo
$i / 100000, "
\n"
;
        }
}
echo
"done.
\n"
;// will echo 'done.'
?>

Daan

1 year ago

If you would like to calculatue the wall time of your script (includes all external DB/HTTP calls etc.) in Unix (in Windows this is already default behavior), you could use the following function:

$timeoutInSeconds

= 3;// This will make sure this is always called async                    
pcntl_async_signals(1);    // Second parameter is any callable (https://www.php.net/manual/en/language.types.callable.php)         
pcntl_signal(SIGALRM, function() {
    exit(
'Stop it!');
});
pcntl_alarm($timeoutInSeconds);                                                                                                         ?>

rycardo74 at gmail dot com

16 years ago

this work to fine html streaming AND time pass limit

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";
?>

ratty at brohoof dot com

10 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.

rsallo at gna dot NOSPAM dot es

19 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.

php at stock-consulting dot com

15 years ago

To find out the currently set time limit, use

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).

alexander dot krause at ed-solutions dot de

11 years ago

A nice workaround to have a real max_execution_time (needs posix and pcntl):

$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);
}
?>

jatin at jatinchimote dot com

16 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.]

ravenswd at gmail dot com

13 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

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:

set_time_limit(2);ob_start();     // buffer outputfunction shutdown () {
   
// print only first 2000 characters of output
   
$out = ob_get_clean();
    print
substr($out, 0, 2000);
}
register_shutdown_function('shutdown');
?>

agvozden at gmail dot com

12 years ago

If you got something like:

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

try this:

        if( !ini_get('safe_mode') ){
           
set_time_limit(25);
        }
?>

bjfieldNO at SPAMgmail dot com

15 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

Silver_Knight

12 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.

Cleverduck

16 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.

BW

13 years ago

If you use Apache you can change maximum execution time by .htaccess with this line

php_value max_execution_time 200

mingalevme at gmail dot com

10 years 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:

require_once('db.php');$stmt = $db->query($sql);

while (

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

How can we increase execution time of a PHP script?

To increase the script execution time, you can use the following snippet at the top of your script. ini_set ( 'max_execution_time' , '300' ); In the above example, it would set the max_execution_time directive to 300 seconds.

How do I increase my max execution time?

Set Max_Execution_Time globally in php..
Locate and open your PHP build folder..
Find the php.ini file and open it..
Find the following line in the text configuration file – max_execution_time=30..
Change the value 30 to the value of choice, Remember, this value is in seconds..
Save & Close..

What is PHP time limit?

By default, the maximum execution time for PHP scripts is set to 30 seconds. If a script runs for longer than 30 seconds, PHP stops the script and reports an error. You can control the amount of time PHP allows scripts to run by changing the max_execution_time directive in your php. ini file.

How do I fix timeout error in PHP?

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.

How can I increase the PHP time limit in WordPress?

There are a number of ways to fix this error..
Method 1: Edit file wp-config. php: Add the following to wp-config. php: ... .
Method 2: Edit file . htaccess: Make sure you back up . htaccess before you edit it. ... .
Method 3: Editing php.ini. Add the following to php.ini: max_execution_time = 300..

How can I increase PHP time limit in cPanel?

Step1: Login to WHM. Step2: Go to Home >> Server Configuration >> Tweak Settings. Step3: Locate the option cPanel PHP max execution time. Step4: Specify the value in seconds.