0
0
PhpDebug / FixBeginner · 4 min read

How to Fix Allowed Memory Size Exhausted Error in PHP

The allowed memory size exhausted error in PHP happens when your script uses more memory than the limit set in php.ini. To fix it, increase the memory_limit setting or optimize your code to use less memory.
🔍

Why This Happens

This error occurs because PHP scripts have a memory limit to prevent them from using too much server memory. When your script tries to use more memory than this limit, PHP stops it and shows the error.

Common causes include loading large files, infinite loops, or inefficient code that uses too much memory.

php
<?php
// Example of code that can cause memory exhausted error
$array = [];
while (true) {
    $array[] = str_repeat('A', 1024 * 1024); // Add 1MB string repeatedly
}
Output
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1048576 bytes) in /path/to/script.php on line X
🔧

The Fix

You can fix this error by increasing the memory_limit in your PHP configuration or at runtime. This allows your script to use more memory.

Alternatively, optimize your code to use less memory by processing data in smaller parts.

php
<?php
// Increase memory limit at runtime
ini_set('memory_limit', '256M');

$array = [];
for ($i = 0; $i < 100; $i++) {
    $array[] = str_repeat('A', 1024 * 1024); // Add 1MB string 100 times
}
echo "Script completed without memory error.";
Output
Script completed without memory error.
🛡️

Prevention

To avoid this error in the future, follow these tips:

  • Set a reasonable memory_limit in php.ini based on your application's needs.
  • Optimize your code to process large data in smaller chunks instead of loading everything at once.
  • Use memory profiling tools to find and fix memory leaks or heavy memory usage.
  • Regularly test your scripts with expected data sizes to ensure memory limits are sufficient.
⚠️

Related Errors

Other errors related to memory issues include:

  • Maximum execution time exceeded: Happens when scripts run too long, often related to heavy processing.
  • Segmentation fault: Rare, but can happen with memory corruption or extensions.
  • Out of memory in database queries: When fetching too much data at once.

Fixes usually involve increasing limits or optimizing code.

Key Takeaways

Increase PHP's memory_limit to allow more memory for your scripts.
Optimize code to use memory efficiently and avoid loading large data all at once.
Use ini_set() to change memory_limit at runtime for quick fixes.
Test scripts with realistic data sizes to prevent memory exhaustion.
Monitor related errors like max execution time to improve script stability.