← Back to Error Lab

PHP Fatal error: Allowed memory size of X bytes exhausted

Published 2026-04-19

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

This error occurs when a PHP script attempts to allocate more memory than the limit defined in the `php.ini` configuration file (`memory_limit`). This is a built-in safeguard to prevent poorly written scripts from consuming all server RAM and crashing the machine. It frequently happens when reading massive files into variables (like `file_get_contents` on a 2GB log file), processing large images using GD, or when an infinite loop continuously appends data to an array. Content Management Systems (CMS) with too many heavy plugins can also trigger this.

Fix / Solution

The quick fix is to increase the `memory_limit` in your `php.ini` file or dynamically via `ini_set('memory_limit', '256M');`. However, this is often a band-aid. The true solution involves optimizing the code: process large files line-by-line using `fopen()` and `fgets()` instead of loading them entirely into memory, use generators for iterating large datasets, and ensure variables holding large data are `unset()` when no longer needed.

Code Snippet

// ❌ Fails on large datasets
$data = $db->fetchAll(); // Loads 1 million rows into RAM
foreach($data as $row) { process($row); }

// ✅ Optimize by unbuffered queries or generators
$stmt = $db->query("SELECT * FROM massive_table");
while ($row = $stmt->fetch()) {
    process($row);
}

// ✅ Temporary memory increase (use with caution)
ini_set('memory_limit', '512M');