PHP Script Timeout
void set_time_limit ( int $seconds )
Where it limits the maximum execution time.
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.
Note: This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini. See here.
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
}
?>
Keep in mind though 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 and in php.ini (comments for ‘max_execution_time’ directive).
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);
}
?>
Unfortunately though, a script which gets into an infinite loop can produce an alarming amount of output in only a few seconds. Try attempting to debug a script, and add this to the beginning of the script:
<?php set_time_limit(2); ?>
But still, even two seconds of run time produced enough output to overload the memory available to the browser.
To work it perfectly, add this to the beginning of the script:
<?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');
?>
A short routine which would limit the execution time, and also limit the amount of output returned.


