Safely catch a 'Allowed memory size exhausted' error in PHP

Safely catch a 'Allowed memory size exhausted' error in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Safely catch a 'Allowed memory size exhausted' error in PHP

When your gateway script returns JSON to a client, you likely expect a consistent response shape even when things go wrong. Using set_error_handler is a common approach to intercept standard errors and return formatted data instead of letting PHP output a raw stack trace or an HTML error page. However, hitting the "Allowed memory size exhausted" limit is different from a standard E_ERROR. In PHP, this condition triggers a fatal error that halts script execution immediately before your custom error handler gets a chance to run.

Attempting to increase the memory limit with ini_set('memory_limit', '19T') might seem like a quick fix for a gateway that needs to process large payloads, but it ignores the architectural reality of how PHP manages resources. Setting a limit as high as 19 terabytes is often impractical and can lead to system instability or swapping issues if the application isn't designed for such loads. Instead of fighting the limit by raising it indefinitely, the goal should be to detect when memory pressure is too high and return a graceful failure message indicating that the user should retry with smaller data or use a different endpoint.

The core problem is that standard error handlers cannot catch fatal errors like E_ERROR (which includes out-of-memory exceptions) unless specific conditions are met. To handle this, you must implement an uncaught exception handler using set_exception_handler. This allows your application to catch the Throwable instance generated when memory runs out and decide how to respond.

Here is a practical pattern for implementing this in PHP:

function handleFatalError($errno, $errstr) {
    if ($errno === E_ERROR && strpos($errstr, 'Allowed memory size exhausted') !== false) {
        // Return a specific JSON response indicating the issue
        http_response_code(507); // 507 Insufficient Storage or custom logic for memory
        echo json_encode([
            'success' => false,
            'error' => 'Memory limit exceeded. Please reduce payload size and try again.',
        ]);
    } else {
        // Let other fatal errors crash the script as usual
        throw new RuntimeException($errstr);
    }
}

function handleFatalException($exception) {
    if ($exception instanceof OutOfMemoryError) {
        http_response_code(507);
        echo json_encode([
            'success' => false,
            'error' => 'Out of memory. Please reduce payload size and try again.',
        ]);
    } else {
        throw $exception; // Re-throw for other fatal exceptions
    }
}

set_error_handler('handleFatalError');
set_exception_handler('handleFatalException');

It is important to note that set_error_handler alone cannot catch the out-of-memory error because PHP treats it as a fatal condition before invoking the handler in some versions, or requires careful configuration. The most robust way to ensure the JSON response is returned is to use register_shutdown_function. This function runs when the script terminates unexpectedly, including when memory is exhausted.

function shutdownMemoryExhausted() {
    if ($this->memoryExceeded) {
        http_response_code(507);
        echo json_encode([
            'success' => false,
            'error' => 'Memory limit exceeded.',
        ]);
        exit;
    }
}

function markMemoryExceeded() {
    $this->memoryExceeded = true;
}

set_error_handler(function($errno, $errstr) use (&$shutdownMemoryExhausted) {
    if ($errno === E_ERROR && strpos($errstr, 'Allowed memory size exhausted') !== false) {
        markMemoryExceeded();
    }
});

register_shutdown_function('shutdownMemoryExhausted');

By using register_shutdown_function, you guarantee that even if the script crashes due to memory exhaustion, your code runs one last time to send the appropriate JSON response. This approach respects the system's resource constraints without requiring massive increases to the global memory_limit. It also prevents the server from returning a generic PHP fatal error page to the client, maintaining the integrity of your API contract.

If you are building complex applications where memory management is critical, frameworks like those offered by LaravelCompany provide built-in mechanisms to handle such scenarios with less boilerplate, but understanding the underlying set_error_handler and shutdown_function mechanics remains essential for low-level control.

Our network