W3docs

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

You can use the set_time_limit() function in PHP to increase the maximum execution time of a PHP script.

The set_time_limit() function in PHP was used to increase the maximum execution time of a script, but it is deprecated in PHP 8.1 and removed in PHP 8.2. Additionally, a 504 Gateway Timeout error typically indicates that nginx timed out waiting for a response from the upstream PHP-FPM process, rather than PHP itself timing out. To resolve 504 errors, you should adjust the timeout settings in nginx and PHP-FPM instead.

Here is an example of how set_time_limit() was historically used:

Example of using the set_time_limit() function to increase the maximum execution time of a PHP script

set_time_limit(30); // Set the maximum execution time to 30 seconds

// Your PHP code goes here

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

Keep in mind that PHP execution limits only affect the script itself. A 504 Gateway Timeout specifically means nginx stopped waiting for the PHP-FPM worker. If the worker is busy or timed out, you may need to look at other factors, such as PHP-FPM pool configuration, server resource utilization, or application performance. Note that increasing PHP execution time without adjusting nginx or PHP-FPM timeouts can prolong 504 errors, as nginx will still cut off the connection after its configured timeout.

You can also adjust the fastcgi_read_timeout directive in the nginx.conf file to increase the amount of time that nginx will wait for a response from the PHP-FPM process. This can help to prevent 504 Gateway Timeout errors in cases where the PHP script is taking a long time to execute.

Example of adjusting the fastcgi_read_timeout directive in the nginx.conf file to increase the amount of time that nginx will wait for a response

fastcgi_read_timeout 300; // Set the timeout to 300 seconds (5 minutes)

Place this directive inside the location ~ \.php$ block or the http/server block in your nginx.conf. After editing, reload nginx with sudo systemctl reload nginx.