PHP Script Keeps Timing Out Despite ini_set

Posted by Paul on April 9, 2018

Occasionally when programming you may need a script to run for quite a long time and unfortunately without changing some settings, the script may timeout before it's finished.

A timeout can occur because of PHP or because of the webserver itself which is often Apache.

To increase the timeout value in PHP for your application, find (or create) the php.ini file in the webroot and add a line such as:

max_execution_time = {number of seconds i.e. 60 for one minute}

It's important to check that your setting has taken effect by using the handy phpinfo() function. Just create a PHP file and add: phpinfo();

When you browse to it, you should get a load of info and if you search the page (with Ctrl + F) you should be able to find max_execution_time and check it's the same as the value you have set.

Always be sure to remove this phpinfo() dump from your site after use because it provides info that could potentially be useful to a hacker.

A better way to increase the timeout is to do it only for the script that you need to take a long time - timeouts exist for a reason - so you can apply it only to your script by adding this at the top:

ini_set('max_execution_time','{number of seconds i.e. 60 for one minute}');

Again check this has been applied by adding phpinfo() below this line in your script.

However, you may find that although phpinfo is showing the value has been set, your script is still timing out. In that case it's likely to be the webserver itself that's causing the problem.

If your webserver is Apache, then you can increase the timeout for that by adding the following to your .htaccess file:

RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]

Hopefully that should ensure that there is no timeout on the webserver itself and the only timeout comes from PHP, which in this case is probably what you want.

Did you find this useful? Do you have any comments? Please let us know below!

blog comments powered by Disqus