Setting time limit in php

set_time_limit

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini .

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

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.

See Also

User Contributed Notes 25 notes

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:

Читайте также:  Box shadow слева css

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 >);\» 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 ))
‘1’ , ‘stdout’ => $stdout , ‘stderr’ => $stderr );
>
$status = proc_get_status ( $process );
posix_setpgid ( $status [ ‘pid’ ], $status [ ‘pid’ ]); //seperate pgid(process group id) from parent’s pgid

stream_set_blocking ( $pipes [ 0 ], 0 );
stream_set_blocking ( $pipes [ 1 ], 0 );
stream_set_blocking ( $pipes [ 2 ], 0 );
fwrite ( $pipes [ 0 ], $stdin );
fclose ( $pipes [ 0 ]);

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 \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 );
?>

Источник

4 Ways To Set Execution Time Limit in PHP (Quick Examples)

Welcome to a tutorial on how to set the execution time limit in PHP. So you want to change the allowed execution time in PHP to prevent timeout errors on a massive script?

There are 4 ways to change the execution time limit in PHP:

  1. Change max_execution_time = SECONDS in php.ini.
  2. On an Apache webserver, add php_value max_execution_time SECONDS in the .htaccess file.
  3. Use set_time_limit(SECONDS) in the PHP script.
  4. Finally, we can set the time limit using ini_set(«max_execution_time», SECONDS) .

That’s all for the basic, read on if you need detailed examples!

TLDR – QUICK SLIDES

How To Set Execution Time Limit in PHP

TABLE OF CONTENTS

WAYS TO SET THE TIME LIMIT

All right, let us now get into the examples of setting the execution time limit in PHP.

METHOD 1) PHP.INI

; Maximum execution time of each script, in seconds ; http://php.net/max-execution-time max_execution_time=180

If you have access to the php.ini file on the server, the easy way is to just change the max_execution_time directive. But please take note that it will be applied to all PHP scripts, I will not recommend doing so unless you intend to do some long processing on the entire server.

METHOD 2) APACHE WEB SERVER – HTACCESS

php_value max_execution_time 180

If you are running an Apache web server, the time limit can also be changed by creating a .htaccess file in the project folder. But take note again, this will apply to the entire project folder.

METHOD 3) INLINE SET TIME LIMIT

This is what I will normally recommend – Change the time limit using the set_time_limit() function in the script itself. This way, it will only apply to this script and not disturb all the other parts unnecessarily.

METHOD 4) ALTERNATIVE TIME LIMIT SET

This final method should be pretty self-explanatory, the ini_set() function allows us to change some of the settings in php.ini during run time. So, Captain Obvious, this example is changing max_execution_time for the duration of the script only.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

EXTRA) COMMAND-LINE SCRIPTS

Please take note that if you run a PHP script in the command line (or terminal), the time limit will automatically be set to 0. That is, there will not be any time limits.

EXTRA) SETTING THE MEMORY LIMIT

Apart from the time limit, you may also run into a memory limit problem when crunching large datasets. Thankfully, this soft limit can also be lifted in a similar manner:

; Maximum amount of memory a script may consume (128MB) ; http://php.net/memory-limit memory_limit=128M
php_value memory_limit 256M

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

How to Increase max_execution_time in PHP

Sajal Soni

Sajal Soni Last updated May 14, 2021

In this quick article, we’ll explore the different options that allow you to increase the maximum amount of time a script is allowed to run before it’s terminated by the parser in PHP.

What Is the max_execution_time Directive in PHP?

The max_execution_time directive sets the maximum amount of time a script is allowed to run before it is terminated. The default is 30 seconds, and you can increase it to a reasonable limit as per your requirements.

More often than not, you will have noticed that if a script takes too long to execute, PHP throws the famous maximum execution time exceeded error:

Fatal error: Maximum execution time of 30 seconds exceeded

In most cases, the max_execution_time directive is not customized, and thus it defaults to 30 seconds, and you could end up with this error.

In the next section, we’ll discuss a couple of different ways to increase the value of the max_execution_time directive.

How to Increase max_execution_time in PHP

There are a few different ways to increase the script execution time.

The ini_set Function

This is one of the easiest ways to increase the value of the max_execution_time directive. The ini_set function is used to change the value of the configuration directives that are available in the php.ini configuration file. And thus, we can use it to change the value of the max_execution_time directive.

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.

On the other hand, if you set it to 0, it would allow the script to run for an infinite amount of time. You must be very careful when you exercise this option, and it’s never recommended in production.

The php.ini Configuration File

If you want to increase the value of the max_execution_time directive globally, you should use this option. Of course, you need permission to change the php.ini file.

Go ahead and locate the php.ini file on your server. If you don’t know how to do it, I explain how to find the php.ini file in another article.

Once you’ve located the php.ini file, open it with your favorite text editor and look for the following line:

; Maximum execution time of each script, in seconds
; https://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI

Change it as per your needs, save it, and restart your web server.

The set_time_limit Function

Apart from the ini_set function which we’ve just discussed, there’s also another PHP function which allows you to set the maximum execution time of a script. The set_time_limit function allows you to set the number of seconds a script is allowed to run.

Let’s quickly look at how the set_time_limit function works.

As you can see, the set_time_limit function takes a single argument: the number of seconds. If you set it to 0, a script is allowed to run for an infinite amount of time.

In fact, the set_time_limit function works a bit differently from the max_execution_time directive. When the set_time_limit function is called, it resets the timeout counter to zero. And from there onward, it measures the script execution time which you’ve set with the set_time_limit function.

Let’s assume that a script is executed for 10 seconds, and then the set_time_limit function is called to set the script execution time to 30 seconds. In that case, a script would run for a total of 40 seconds before it’s terminated. So if you want to use the set_time_limit function to set the maximum execution time of a script, you should place it at the top of your script.

Apache Users: The .htaccess File

If you’re using the Apache server to power your website, it provides the .htaccess configuration file, which allows you to set php.ini configuration directives. In this section, we’ll see how you can use the .htaccess file to set the max_execution_time directive.

First of all, you need to locate the .htaccess file in your project. In most cases, you should be able to find it in the document root of your project. If you can’t find it in the project root, you need to make sure that it’s not hidden by your file manager software, since the dot before the .htaccess file name indicates that it is a hidden file. You can use the show hidden files option in your file manager to see all the hidden files in your document root. If you still can’t find it, you need to create one.

Open the .htaccess file in your favorite text editor and add the following line at the end.

php_value max_execution_time 300

Conclusion

Today, we discussed a few different ways to change the value of the max_execution_time directive in PHP.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Источник

Оцените статью