Resolving PHP Maximum Execution Time Exceeded on Ubuntu 22.04 LTS (max_execution_time)
Fix the 'PHP maximum execution time of 30 seconds exceeded' error on Ubuntu 22.04 LTS servers. Learn to adjust php.ini and web server timeouts for optimal script performance.
Fix the 'PHP maximum execution time of 30 seconds exceeded' error on Ubuntu 22.04 LTS servers. Learn to adjust php.ini and web server timeouts for optimal script performance.
A PHP script exceeding its allowed execution time is a common challenge for web applications, especially when dealing with complex calculations, large data processing, or slow external API calls. When this limit is hit, your web application will likely fail to load completely, presenting an error to the user or failing silently. This guide will walk you through diagnosing and resolving the "PHP maximum execution time of 30 seconds exceeded" issue on Ubuntu 22.04 LTS systems, focusing on common Nginx and PHP-FPM setups.
Symptom & Error Signature
Users typically encounter a blank page, an HTTP 500 Internal Server Error, or an HTTP 504 Gateway Timeout (if Nginx or another web server's timeout is shorter than PHP's).
The primary indicator of this problem resides in your PHP-FPM error logs (e.g., /var/log/php8.1-fpm.log or /var/log/nginx/error.log if Nginx reports it).
PHP Error Log Example:
[DATE TIME] [error] [pid 12345] PHP Fatal error: Maximum execution time of 30 seconds exceeded (tried to allocate 20480 bytes) in /var/www/your_app/public/index.php on line 42
Nginx Error Log Example (often seen if Nginx times out waiting for PHP-FPM):
[DATE TIME] [error] 1234#1234: *1234 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.1.1, server: example.com, request: "GET /long-running-script.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.1-fpm.sock", host: "example.com"
Root Cause Analysis
The "PHP maximum execution time exceeded" error stems from a configurable directive within PHP's runtime environment, specifically max_execution_time. This directive dictates the maximum number of seconds a PHP script is allowed to run. By default, it's often set to 30 seconds.
However, the problem can be compounded or masked by timeouts at different layers of your web stack:
max_execution_time(PHP-FPM/CLI): This is PHP's internal timer. If a script runs longer than this, PHP will terminate it and log a fatal error.max_input_time(PHP-FPM/CLI): This PHP directive defines the maximum time in seconds a script is allowed to parse input data (like POST or GET data). While less common for "execution time" errors, a large upload or complex input can trigger it.- Web Server FastCGI Timeout (Nginx/Apache): If you're using Nginx or Apache with PHP-FPM, the web server itself has a timeout for waiting on PHP-FPM. If PHP-FPM is busy executing a long script (even one within its
max_execution_timelimit), but Nginx'sfastcgi_read_timeoutis shorter, Nginx will kill the connection and report a 504 Gateway Timeout, even if PHP itself hasn't hit itsmax_execution_time. - Script Inefficiency: While increasing timeouts can resolve the immediate error, the root cause is often an inefficient PHP script. This could involve unoptimized database queries, heavy file I/O operations, slow external API calls, or complex algorithmic processing.
- Resource Exhaustion: Insufficient CPU or memory resources on the server can make scripts run slower than expected, causing them to hit execution time limits prematurely.
Step-by-Step Resolution
To effectively resolve this, we need to adjust timeouts at both the PHP and web server levels.
1. Identify Your PHP-FPM Version and Configuration Files
First, determine which PHP version your application is using, as configuration files are version-specific.
php -v
Output will look something like:
PHP 8.1.2-1ubuntu2.14 (cli) (built: Aug 18 2023 11:27:06) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
with Zend OPcache v8.1.2-1ubuntu2.14, Copyright (c), by Zend Technologies
In this case, it's PHP 8.1. Your PHP-FPM configuration will typically be under /etc/php/8.x/fpm/.
To confirm the exact php.ini file being loaded by PHP-FPM:
php-fpm8.1 -i | grep 'Loaded Configuration File'
(Replace php-fpm8.1 with your specific version, e.g., php-fpm8.2). This might not directly show the FPM config, but the CLI one, which usually points to the same fpm/ directory for the relevant php.ini. A better way is to check the FPM pool configuration.
For PHP-FPM, the main php.ini is usually found in /etc/php/8.x/fpm/php.ini. If you also run scripts from the command line that hit this error, you might need to adjust /etc/php/8.x/cli/php.ini.
2. Adjust max_execution_time and max_input_time in php.ini
Open the php.ini file for your PHP-FPM service using a text editor:
sudo nano /etc/php/8.1/fpm/php.ini
Locate the max_execution_time and max_input_time directives and increase their values. A common starting point for longer tasks is 300 seconds (5 minutes), but adjust based on your script's actual needs.
; Maximum execution time of each script, in seconds
; https://php.net/max-execution-time
max_execution_time = 300
; Maximum amount of time each script may spend parsing request data.
; https://php.net/max-input-time
max_input_time = 300
While increasing these values resolves the immediate error, setting them excessively high (e.g., 0 for unlimited) is generally discouraged for production environments. It can allow runaway or poorly optimized scripts to consume all server resources, leading to Denial of Service (DoS) for other applications or users. Always prioritize script optimization over indefinite timeouts.
Save the file and exit the editor.
3. Adjust Nginx FastCGI Timeout Settings
If you are using Nginx as your web server (which is common on Ubuntu 22.04 LTS), you also need to ensure that Nginx is patient enough to wait for PHP-FPM to complete the script execution. Otherwise, Nginx will timeout and return a 504 Gateway Timeout error, even if PHP's max_execution_time is higher.
Open your Nginx site configuration file. This is typically found in /etc/nginx/sites-available/your_site.conf (or default if you haven't created a specific site config).
sudo nano /etc/nginx/sites-available/your_site.conf
Inside the location ~ .php$ block, add or adjust the following fastcgi_*_timeout directives. These values should be greater than or equal to your max_execution_time set in php.ini.
server {
# ... other server configurations ...
location ~ .php$ {
include snippets/fastcgi-php.conf; # Common include
fastcgi_pass unix:/run/php/php8.1-fpm.sock; # Adjust PHP-FPM socket path
# Set FastCGI timeouts - ensure these are >= max_execution_time in php.ini
fastcgi_read_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_connect_timeout 300s;
}
# ...
}
The
fastcgi_passdirective's socket path (unix:/run/php/php8.1-fpm.sock) must match the actual socket used by your PHP-FPM service. Verify this by checking thelistendirective in your PHP-FPM pool configuration file, usually/etc/php/8.1/fpm/pool.d/www.conf.
Save the Nginx configuration file.
4. Restart Services
For the changes to take effect, you must restart the PHP-FPM service and reload the Nginx configuration.
sudo systemctl restart php8.1-fpm
sudo systemctl reload nginx
Always test your Nginx configuration before reloading to catch syntax errors:
sudo nginx -t. If it reportssyntax is okandtest is successful, thensudo systemctl reload nginxis safe.
5. Verify Changes (Optional but Recommended)
You can quickly verify that your PHP settings have been updated by creating a phpinfo.php file in your web root:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/your_app/public/phpinfo.php
Then, access http://your_domain.com/phpinfo.php in your browser and search for max_execution_time and max_input_time. Delete the phpinfo.php file immediately after verification for security reasons.
sudo rm /var/www/your_app/public/phpinfo.php
Alternatively, you can query PHP's configuration from the command line:
php -i | grep max_execution_time
php -i | grep max_input_time
Keep in mind that php -i shows the CLI settings, not necessarily the FPM ones, unless you've also updated /etc/php/8.1/cli/php.ini. For PHP-FPM specific settings, the phpinfo() output through the web server is more accurate.
6. Consider Script Optimization and Asynchronous Processing
While extending timeouts is a valid short-term solution, it doesn't address the underlying inefficiency of a long-running script. For tasks that genuinely require extended processing beyond a few minutes, consider alternative approaches:
- Asynchronous Tasks: Move long-running operations (e.g., image processing, report generation, bulk email sending) into background jobs using message queues (e.g., Redis with Laravel Queue, RabbitMQ, AWS SQS) and dedicated worker processes.
- Cron Jobs: For scheduled, heavy batch processes, use cron jobs that run PHP scripts directly from the CLI, which has its own
max_execution_time(often-1or very high by default incli/php.ini) or can be overridden per script. - Database Optimization: Ensure your database queries are optimized, indexed, and efficient.
- Code Profiling: Use tools like Xdebug to profile your PHP scripts and identify bottlenecks.
By combining appropriate timeout settings with smart application design, you can ensure your web applications run smoothly and efficiently without hitting execution limits.
Our Production Verification Guarantee
Encountering a bug not covered here or running a non-standard kernel configuration? Our solutions are continually refined against real production incidents. Submit an environment trace for our editorial team to replicate.