When a PHP script crashes with Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate ...), the worst instinct in production is setting memory_limit = -1 or bumping it blindly to 2G. A single controller hitting a 512 MB export or recursive loop under 20 concurrent PHP-FPM requests quickly consumes 10 GB of server RAM, triggers the Linux kernel OOM killer, and drops neighboring traffic with Nginx 502 Bad Gateway errors. The durable fix is finding the hidden allocation spike and streaming data in bounded memory instead.

Root Causes: Where PHP Scripts Quietly Burn Hundreds of Megabytes

Allocation Culprit Why Memory Spikes Suddenly Bounded-Memory Replacement
PDO::fetchAll() on large tables Buffers every row into PHP zval hashtables simultaneously (typically 4–8× raw SQL size) Stream row by row with while ($row = $stmt->fetch()) + PHP Generators (`yield`)
ORM / ActiveRecord entity hydration Instantiating 50,000 Model/Entity objects copies metadata, casts, and event closures per row Switch read-only exports to plain arrays (`asArray()`) and chunked pagination (`chunk(500)`)
Loading full JSON / CSV files into RAM json_decode(file_get_contents('huge.json'), true) allocates deep PHP associative arrays Stream NDJSON line-by-line via fgets() or parse chunks cleanly
imagecreatefromjpeg() on high-res photos Decompressed GD bitmaps require ~width × height × 4 bytes × 1.8 RAM regardless of compressed KB size! Validate pixel dimensions with getimagesize() first; enforce max megapixels before decoding
Unbounded Composer/log buffers in workers Long-running queues or debug query loggers accumulate every SQL query in RAM Restart queue workers cleanly (`--max-jobs=250`) and disable query logging during bulk imports

1. Measure Exactly Where Memory Jumped Before Guessing

Never optimize blind. Wrap suspect stages of a CLI script or staging endpoint with memory_get_usage(true) and memory_get_peak_usage(true) to pinpoint which function blew the budget:

<?php
function logMemoryStage(string $stage): void
{
    $currentMb = round(memory_get_usage(true) / 1048576, 2);
    $peakMb    = round(memory_get_peak_usage(true) / 1048576, 2);
    error_log(sprintf('[mem:%s] current=%.2f MB peak=%.2f MB', $stage, $currentMb, $peakMb));
}

logMemoryStage('boot');
// ... run query or transform ...
logMemoryStage('after_export');

Notice the true flag: passing true reports actual system pages allocated by Zend Engine rather than internal small-block estimates, matching the limit enforced by memory_limit.

2. Replace fetchAll() With Unbuffered PDO + Generators (yield)

By default, PHP's MySQL driver (`mysqlnd`) buffers the entire result set inside C memory before returning from execute(). Even if you iterate with foreach, PHP already allocated space for all matching rows. Disabling buffered queries on dedicated export connections and yielding one row at a time drops RAM usage to constant O(1) memory:

<?php
declare(strict_types=1);

/**
 * Streams millions of rows in constant RAM over a dedicated unbuffered PDO handle.
 */
function streamOrders(PDO $exportPdo, string $sinceDate): Generator
{
    // Critical: use a separate connection if executing other queries inside the consumer loop
    $exportPdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

    $stmt = $exportPdo->prepare(
        'SELECT id, customer_email, total_cents, created_at
         FROM orders
         WHERE created_at >= :since
         ORDER BY id ASC'
    );
    $stmt->execute(['since' => $sinceDate]);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        yield $row;
    }
}

Remember MySQL's single-active-unbuffered-query rule: while an unbuffered result set stays open on a connection, you cannot execute nested SELECT or UPDATE queries on that exact same PDO instance until the cursor finishes or closes (`$stmt->closeCursor()`).

3. Stream Large CSV & JSON Downloads Directly to php://output

Building a 100 MB CSV string via $csv .= ... or encoding 100,000 objects in one json_encode($rows) call doubles peak memory unnecessarily. Write chunks straight to php://output cleanly:

<?php
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="orders-export.csv"');

// Avoid buffering the entire response inside PHP output buffers
while (ob_get_level() > 0) {
    ob_end_clean();
}

$out = fopen('php://output', 'wb');
fputcsv($out, ['Order ID', 'Email', 'Total Cents', 'Created At']);

$count = 0;
foreach (streamOrders($exportPdo, '2026-01-01 00:00:00') as $row) {
    fputcsv($out, [$row['id'], $row['customer_email'], $row['total_cents'], $row['created_at']]);
    if ((++$count % 500) === 0) {
        fflush($out);
    }
}
fclose($out);

If clients consume huge JSON datasets cleanly in the browser without blowing up server RAM, export newline-delimited JSON (.ndjson) one line per record and inspect slices safely using our Large JSON Browser Streaming Guide.

4. Prevent CodeIgniter 4 / Eloquent Hydration & Query Log Leaks

ORMs and framework query profilers secretly accumulate memory during background loops in two ways:

  • Debug Query History Array: Framework database wrappers in development mode append every executed SQL statement (`$db->getLastQuery()` / query collector arrays) into memory. Inside batch CLI importers or seeders running 20,000 inserts, periodically reset logs or batch inserts cleanly (`insertBatch($chunk, null, 500)`).
  • Full Entity Instantiation: Fetching 10,000 rows via `->findAll()` builds 10,000 Entity objects. Chain `->asArray()` (or use keyset pagination `WHERE id > $lastId ORDER BY id LIMIT 1000`) whenever rendering exports or reports.
<?php
// Keyset cursor loop in CodeIgniter 4: flat memory footprint + indexed O(log N) seeks
$lastId = 0;
do {
    $rows = $db->table('audit_events')
        ->select('id, event_type, created_at')
        ->where('id >', $lastId)
        ->orderBy('id', 'ASC')
        ->limit(1000)
        ->get()
        ->getResultArray();

    foreach ($rows as $row) {
        processEvent($row);
        $lastId = (int) $row['id'];
    }
} while (count($rows) === 1000);

5. Guard GD / Image Processing Against Compressed Decompression Bombs

A tiny 600 KB smartphone JPEG compressed at 6000 × 4000 pixels (24 MP) expands inside GD to roughly 6000 × 4000 × 4 bytes ≈ 96 MB of raw RGBA buffers—plus internal working copies pushing a 128 MB script past its cap! Check pixel counts cleanly before opening any image:

<?php
[$width, $height] = getimagesize($uploadTmpPath) ?: [0, 0];
$pixels = $width * $height;

if ($width === 0 || $pixels > 25_000_000) {
    throw new RuntimeException('Image pixel dimensions exceed safe processing cap.');
}

6. Right-Sizing memory_limit Alongside PHP-FPM Pools

Once streaming fixes are in place, calculate capacity explicitly: Total FPM RAM = pm.max_children × avg_worker_MB. On a 2 GB VPS reserving ~600 MB for Linux + MariaDB, running 12 PHP-FPM children leaves ~115 MB average headroom—so setting memory_limit = 128M for web HTTP requests and moving heavy reports/imports into bounded CLI queue jobs keeps web responses responsive. Review full pool math in our PHP-FPM 502 tuning guide and explore the PHP Engineering Hub.

Frequently Asked Questions

Why is PHP exhausting memory right on line 1 or inside Composer autoloading?

Normally a bloated config array, corrupt opcode cache, recursive function without a base case, or error handler logging giant objects in stack frames consumes RAM earlier before triggering at the next allocation request.

Does calling unset($hugeArray) immediately return RAM to PHP?

Calling unset() drops the variable reference so Zend Engine reuses the memory internally (and `gc_collect_cycles()` frees circular object graphs), though Linux OS resident memory only shrinks noticeably when large blocks free.

Is memory_limit = 256M acceptable for modern PHP apps?

Yes for complex CMS/admin endpoints if PHP-FPM `pm.max_children` respects total server RAM, whereas public frontend routes and APIs should usually stay well under 32–64 MB peak usage.