How to Increase PHP max_execution_time for One Script
This article explains how to temporarily increase the execution time
limit for a specific PHP script without altering your global server
configuration. You will learn about the two primary PHP functions used
to override the default max_execution_time setting
dynamically, how to implement them in your code, and the external server
factors you must consider to ensure your long-running scripts complete
successfully.
Method 1: Using set_time_limit()
The most common and straightforward way to increase the execution
time for a specific script is by using the built-in PHP function
set_time_limit().
When called, this function restarts the timeout counter from zero.
This means if your default limit is 30 seconds, and you call
set_time_limit(60) after the script has already run for 10
seconds, the script will be allowed to run for a total of 70
seconds.
Place this line at the very top of the PHP file you want to extend:
<?php
// Set the maximum execution time for this script to 120 seconds
set_time_limit(120);
// Your long-running code goes hereIf you want to remove the execution time limit entirely, pass
0 to the function:
<?php
// Disable the time limit completely (use with caution)
set_time_limit(0);Method 2: Using ini_set()
Alternatively, you can use the ini_set() function to
modify the max_execution_time configuration option directly
within your script. This achieves the same result as
set_time_limit().
Add the following code to the beginning of your PHP file:
<?php
// Increase execution time to 5 minutes (300 seconds)
ini_set('max_execution_time', '300');
// Your long-running code goes hereLike the previous method, setting this value to '0' will
allow the script to run indefinitely:
<?php
ini_set('max_execution_time', '0');Critical Caveats and Web Server Limitations
Even if you successfully increase the execution limit in PHP, your script may still time out due to server-level limits. You should keep the following factors in mind:
- Hosting Restrictions: If your PHP environment is
running in
safe_mode(deprecated but present in very old PHP versions) or hasset_time_limitdisabled in thedisable_functionsdirective ofphp.ini, these runtime changes will have no effect. - Web Server Timeouts: Apache and Nginx have their
own timeout limits. For example, if you are using Nginx with PHP-FPM,
the
fastcgi_read_timeoutsetting in your Nginx configuration might cut off the connection after 60 seconds, regardless of your PHP settings. - Browser Timeouts: If a script takes too long to
respond, the user’s web browser may drop the connection. For highly
intensive tasks, it is best practice to run the script via the Command
Line Interface (CLI), where the execution time limit is usually set to
unlimited (
0) by default.