Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set max_execution_time in PHP CLI

I know that PHP CLI is usually used because of none time limits and primary because it is not using Apache threads/processes.

But is there any way how to explicitly set the max_execution_time for some scripts which i don't want to have the freedom of "unlimited time" and just want to keep those script under control?

If you think this question may be better answered on superuser.com and have permission to move it, do it. :)

Edit: I've been Googling a bit and found the right parameter:

php -d max_execution_time=5 script.php 
like image 820
Radek Simko Avatar asked May 03 '11 19:05

Radek Simko


People also ask

What is max_execution_time in PHP?

max_execution_time int. This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30 . When running PHP from the command line the default setting is 0 .

How do we set an infinite execution time for PHP script?

Yes, it is possible to set an infinite execution time for the PHP Script. We can do it by adding the set_time_limit() function at the beginning of the PHP script. The set_time_limit() function takes only one parameter that is int value which is in seconds and it returns a boolean value.


2 Answers

The documentation says that when running in command line mode, the default is 0 (unlimited). It doesn't say that you cannot override it:

set_time_limit(10); // this way ini_set('max_execution_time', 10); // or this way 

Edit: I just tried it myself, and it works as expected.

F:\dev\www>c:php -f index.php PHP Fatal error:  Maximum execution time of 2 seconds exceeded in F:\dev\www\index.php on line 3  Fatal error: Maximum execution time of 2 seconds exceeded in F:\dev\www\index.php on line 3 
like image 178
Jon Avatar answered Sep 20 '22 12:09

Jon


set_time_limit() works in CLI scripts.

<?php  set_time_limit(1); //in seconds for (;;); ?> 

After one second returns with the following error message:

PHP Fatal error:  Maximum execution time of 1 second exceeded in \ /home/stivlo/test.php on line 4 

Initially I tried with sleep() and the time limit doesn't get applied. As @Jon suggested, using a real computation, like an infinite loop works.

I found this interesting comment in the sleep() PHP page:

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(), the sleep() function, database queries, etc. is not included when determining the maximum time that the script has been running

like image 44
stivlo Avatar answered Sep 20 '22 12:09

stivlo