3 * Expansion of the PHP execution time limit feature for a function call.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Class to expand PHP execution time for a function call.
25 * On construction, set_time_limit() is called and set to $seconds.
26 * When the object goes out of scope, the timer is restarted, with
27 * the original time limit minus the time the object existed.
29 class ScopedPHPTimeout
{
30 protected $startTime; // float; seconds
31 protected $oldTimeout; // integer; seconds
33 protected static $stackDepth = 0; // integer
34 protected static $totalCalls = 0; // integer
35 protected static $totalElapsed = 0; // float; seconds
37 /* Prevent callers in infinite loops from running forever */
38 const MAX_TOTAL_CALLS
= 1000000;
39 const MAX_TOTAL_TIME
= 300; // seconds
42 * @param $seconds integer
44 public function __construct( $seconds ) {
45 if ( ini_get( 'max_execution_time' ) > 0 ) { // CLI uses 0
46 if ( self
::$totalCalls >= self
::MAX_TOTAL_CALLS
) {
47 trigger_error( "Maximum invocations of " . __CLASS__
. " exceeded." );
48 } elseif ( self
::$totalElapsed >= self
::MAX_TOTAL_TIME
) {
49 trigger_error( "Time limit within invocations of " . __CLASS__
. " exceeded." );
50 } elseif ( self
::$stackDepth > 0 ) { // recursion guard
51 trigger_error( "Resursive invocation of " . __CLASS__
. " attempted." );
53 $this->oldTimeout
= ini_set( 'max_execution_time', $seconds );
54 $this->startTime
= microtime( true );
56 ++self
::$totalCalls; // proof against < 1us scopes
62 * Restore the original timeout.
63 * This does not account for the timer value on __construct().
65 public function __destruct() {
66 if ( $this->oldTimeout
) {
67 $elapsed = microtime( true ) - $this->startTime
;
68 // Note: a limit of 0 is treated as "forever"
69 set_time_limit( max( 1, $this->oldTimeout
- (int)$elapsed ) );
70 // If each scoped timeout is for less than one second, we end up
71 // restoring the original timeout without any decrease in value.
72 // Thus web scripts in an infinite loop can run forever unless we
73 // take some measures to prevent this. Track total time and calls.
74 self
::$totalElapsed +
= $elapsed;