How to Fix "Fatal Error: Allowed Memory Size of X Bytes Exhausted" in PHP
Google AdSense In-Article Display Placement
Publisher ID: ca-pub-XXXXXXXXXXXXXXXX (Configured in config.php)When a PHP script attempts to allocate more RAM than allowed by memory_limit (e.g. 128MB or 256MB), PHP halts execution. Discover how to increase memory limits cleanly and optimize unbuffered SQL queries.
Edit your php.ini file and change "memory_limit = 128M" to "memory_limit = 512M", then restart your web server. In WordPress, add "define('WP_MEMORY_LIMIT', '256M');" inside "wp-config.php". For custom scripts, use "ini_set('memory_limit', '512M');" at the top.
📋 Guide Table of Contents
1. Problem Diagnosis & Symptoms
Processing high-resolution images or fetching 50,000 database rows into memory at once exceeds standard RAM caps.
2. Primary Root Causes
- Cause: Fetching all database rows into array instead of streaming.
- Cause: Processing multi-megapixel images using GD library.
3. Step-by-Step Diagnostic Fixes
Increase Limit in php.ini
Edit php.ini directive:
memory_limit = 512M
4. How to Verify the Resolution
- Check phpinfo() for updated memory_limit.
5. Diagnostic Troubleshooting Matrix
| Symptom Observed | Root Cause | Recommended Action |
|---|---|---|
| Memory exhausted during image resize | GD library decompresses entire bitmap into RAM | Increase memory_limit to 512M or switch to Imagick |
6. Critical Mistakes to Avoid
- ❌ Setting memory_limit = -1 in production.
7. Frequently Asked Questions
❓ Why does the error message display numbers in bytes?
PHP prints raw bytes: 134217728 bytes equals exactly 128 Megabytes.
Official Technical References
Google AdSense In-Article Matched Content Unit