PHP Limit Execution Time

If you ever had to run an important PHP task that take quite a long time to get completed you may have come across this kind of error message:
Fatal error: Maximum execution time of 30 seconds exceeded
As you probably can understand this is due to the PHP task taking more than 30 seconds to finish its execution. 30 seconds is the maximum time allocated by default.

How To Avoid This Message

This limitation offers some security but can also be a problem in some cases. Let’s say that you are in charge of updating 100.000 products in a database for an ecommerce website. Updating all products at once will take more than 30 seconds believe me. So what you could do is update the data one by one…please tell me you’re not going to do that.
Another solution would be to update by chunks. For example execute you script on the products 1 to 10.000 and then products 10.001 to 20.000 and so on. But this is time consuming and not very professional.
Now let’s look at the best and easiest approach, I know you’ve been waiting for that moment. The following script is a PHP function that allows you to change this time limitation.

PHP

<?php
/*Add one of the following functions before your script*/
ini_set('max_execution_time', 300);
    
/*This function does exactly the same, it is just shorter.*/
set_time_limit(300);
?>

The value 300 is the time in seconds and this can be change to fit your needs. Setting the time to 0 means no time limit(not recommended).

Note

Be aware that these functions won’t work if PHP SAFE MODE is configured. If this is the case you will have to changing the time limit directly in the php.ini file.

Leave a Reply

Your email address will not be published. Required fields are marked *