PHP max_execution_time explained


The crucial part of PHP application maintenance and performance issue mitigation is an understanding of the PHP and server limits (configuration). However, they are not that straightforward as we tend to think. In this article, I will explain and give examples of the PHP max_execution_time configuration limit, which in some situations behaves differently than you would expect. 

From the documentation 

The maximum execution time is not affected by system calls, stream operations etc. Please see the set_time_limit() function for more details.

These days this paragraph is significant because PHP applications mostly use their time performing that type of operations. And it means your script can actually take more time to finish than your configuration limit. In other words, it can take more time than you expect.

The max_execution_time limit in action

The following script changes the max_execution_time to 5 seconds (the default PHP max_execution_time is 30 seconds) and performs the endless loop to fill up the execution time.

As we can see, the script was allowed to run for ~5 seconds until it resulted in the 500 status code triggered by the max_execution_time limit:

In the following examples, I'm going to extend this code.

1) SQL queries, Redis, Memcached or any other TCP connection

The time spent executing SQL queries is not counted. For example, you have a script that has a SQL query, and it's execution takes 10 seconds. It means the script will be allowed to run 15 seconds in case if the max_execution_time is set to 5 seconds.

The following example is the way to test it:

As we can see, the script execution time does not include the SQL query execution time.

The same would apply to any other external TCP calls such as:

  • Memcached
  • MongoDB
  • Redis

2) 3rd party HTTP API calls

I decided to make this as a separate paragraph to clearly show that HTTP request (TCP communication) does not count towards the limit.

3) System calls

The total execution time is 20 seconds because 15 seconds of the system call does not count towards the max_execution_time limit.

4) Filesystem calls

Interaction time (such as fwrite) with the filesystem is not limited by max_execution_time.

5) Sleep methods

As we can see, the sleep or usleep methods are not counted towards the max_execution_time limit.

Closing Note 

I hope this article gave you an idea about the max_execution_time setting nature and what to expect from it. Knowing these aspects, in situations where you would like to limit the PHP execution time, you may probably want to consider using the server or PHP-FPM limits instead of max_execution_time