← All posts

PHP “Maximum execution time of 30 seconds exceeded”: find the cause and fix it (without just raising the limit)

What max_execution_time really measures, how to find the slow code, when and where to raise the limit (PHP, .user.ini, nginx), and how to move long-running jobs out of the web request.

PHP "Maximum execution time of 30 seconds exceeded": find the cause and fix it (without just raising the limit)

Key points

  • The error shows the line PHP was on when it was stopped, not necessarily the code that used up the time: measure before you fix.
  • Raising max_execution_time achieves nothing if nginx, PHP-FPM or a proxy cuts the request off first.
  • Long jobs (imports, PDF generation, bulk emails) don’t belong in a web request: split them up or run them in the background.

Fatal error: Maximum execution time of 30 seconds exceeded. It hits during a product import, a plugin update or a report export, and leaves you with a blank page. The usual reflex is to bump the limit to 300 seconds and move on. Sometimes that’s justified; more often it just moves the problem: the page now takes four minutes to fail, or runs into another timeout nobody had noticed. On our projects we handle this error in three steps: understand what’s being measured, find what’s slow, then choose between speeding up the code, adjusting limits in the right place, or taking the job out of the request altogether.

What the error really means

The max_execution_time directive sets how long a PHP script may run. It defaults to 30 seconds, and to 0, meaning unlimited, on the command line. When the limit is reached, PHP stops the script dead and reports whichever file and line it happened to be on.

Another documented but little-known subtlety: on Linux, the time counted is time the script spends computing. Waiting on the network, database queries, file reads or sleep() don’t count. So a page waiting a full minute for a slow API often won’t trigger this error at all; it ends in a 504 Gateway Timeout instead, cut off by the web server. When you do see PHP’s error, look for computation first: loops, image processing, large datasets held in memory, expensive regular expressions.

Find the code that takes the time

Measure before touching any limit. The simplest way is to time the main steps of the job and write the durations to the error log:

$t0 = hrtime(true);
$orders = fetchOrders();      // step 1
error_log(sprintf('orders: %.0f ms', (hrtime(true) - $t0) / 1e6));

$t0 = hrtime(true);
$pdf = generateInvoices($orders);     // step 2
error_log(sprintf('invoices: %.0f ms', (hrtime(true) - $t0) / 1e6));

On a server where you control PHP-FPM, the slow request log is even better, because it records the stack trace of slow requests without any code changes:

; PHP-FPM pool, for example /etc/php/8.3/fpm/pool.d/www.conf
; Any request running longer than 5 s gets its stack trace written to this file
request_slowlog_timeout = 5s
slowlog = /var/log/php-fpm/www-slow.log

On WordPress, the Query Monitor plugin shows generation time, the slowest SQL queries and outgoing HTTP calls for every page. For a job started from the admin, that’s often enough to pin down the plugin responsible.

The causes we run into most: an import processing thousands of rows in a single request; regenerating thumbnails for an entire media library; a loop running one SQL query per item instead of a single grouped query; a calculation redone on every pass instead of being cached; and, more rarely, an infinite loop after some unexpected change in the data.

Raising the limit: when it’s legitimate, and where

Raising the limit is reasonable for a one-off, known and bounded job: a monthly export run by an administrator, a migration. It isn’t for a public page: if a page your visitors see takes more than 30 seconds to build, the page is the problem.

The limit can be set at several levels:

// 1. For one specific script, deliberately
set_time_limit(300); // the counter restarts from zero at this call

; 2. .user.ini file in the site root (PHP-FPM or CGI)
max_execution_time = 120

# 3. nginx: don't drop the connection before PHP has finished
location ~ .php$ {
    fastcgi_read_timeout 120s;
}

set_time_limit() applies to the current script and resets the counter at the moment it’s called. Some shared hosts disable it, in which case the call is ignored with a warning. A .user.ini file applies to its folder and subfolders, but PHP only re-reads it periodically, every five minutes by default. We’ve seen developers edit the file, test immediately and wrongly conclude it doesn’t work. php_value lines in .htaccess only work when PHP runs as an Apache module, and cause a 500 error in any other setup.

Above all, PHP isn’t the only clock running. The web server (fastcgi_read_timeout on nginx, Timeout or the proxy timeout on Apache), PHP-FPM itself through request_terminate_timeout, and any load balancer or CDN in front of the site each have their own timeout. The shortest one wins. Raise max_execution_time to 300 seconds while the proxy gives up much earlier, and the visitor gets a 504 while PHP keeps working for nothing.

The real fix: take long jobs out of the request

A web request is meant to answer in a few hundred milliseconds. Anything that can take minutes, such as an import, an export, generating dozens of PDFs or a bulk email send, should run somewhere else. Two approaches cover most cases.

The first is to run the job from the command line, where there’s no time limit by default, and split it into batches to keep memory and transactions under control:

<?php
// import-products.php, run from the command line (by hand or from cron):
// php import-products.php products.csv
require __DIR__ . '/config.php'; // defines $dsn, $user and $pass

$file = new SplFileObject($argv[1]);
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD
                   | SplFileObject::SKIP_EMPTY);

$pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare('INSERT INTO products (sku, name, price) VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE name = VALUES(name), price = VALUES(price)');

$n = 0;
$pdo->beginTransaction();
foreach ($file as $i => $row) {
    if ($i === 0 || count($row) < 3) {
        continue; // header or incomplete row
    }
    $stmt->execute([$row[0], $row[1], $row[2]]);
    if (++$n % 500 === 0) {   // commit in batches of 500 rows
        $pdo->commit();
        $pdo->beginTransaction();
        echo "$n rowsn";
    }
}
$pdo->commit();
echo "Done: $n rowsn";

The second approach, for jobs a user triggers from the interface, is to queue the work and respond straight away. On WordPress, the Action Scheduler library, the one WooCommerce relies on, does this very well:

// When "Generate invoices" is clicked: schedule instead of computing
foreach ($order_ids as $id) {
    as_enqueue_async_action('agency_generate_invoice', ['order' => $id], 'invoices');
}

// Runs in the background, one order at a time
add_action('agency_generate_invoice', function (int $order) {
    agency_create_invoice_pdf($order);
});

Each task is short, a failure in one doesn’t stop the others, and the WooCommerce or Action Scheduler admin screen shows what succeeded and what failed. In the interface, show a “Generating…” status and tell the user when it’s done, with a notification or an email. On custom applications, we apply the same principle with a proper message queue and workers.

FAQ

Is setting max_execution_time to 0 dangerous?

For web requests, yes: a script stuck in a loop will hold a PHP process forever, and a handful of those is enough to bring the server down. Keep the unlimited setting for the command line, where it’s already the default.

The error happens during a WordPress update. What should I do?

Run the update once more: a briefly overloaded server can be enough to explain it. If it fails again, run it with WP-CLI (wp plugin update or wp core update), which has no time limit, after taking a backup.

Failing imports, never-ending exports, admin pages that time out: we track down what’s slowing your PHP or WordPress application and set up reliable background processing.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →