Resolving the 'Allowed memory size exhausted' PHP error message
When running PHP applications such as WordPress, Drupal, or custom scripts, you may encounter the error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 33554432 bytes) in /home/example/public_html/filename.php on line 1622This indicates that your script has used more memory than PHP is allowed to allocate.
Why This Happens
Section titled “Why This Happens”- The application consumes more memory than the default PHP limit.
- Large plugins, themes, or modules require additional resources.
- Inefficient code that does not release memory properly.
- Heavy database queries or large file processing.
Solutions
Section titled “Solutions”1. Optimize Your Code
Section titled “1. Optimize Your Code”- Use
unset()to destroy variables and objects no longer needed. - Avoid loading large datasets into memory at once.
- Break tasks into smaller chunks.
2. Increase PHP Memory Limit
Section titled “2. Increase PHP Memory Limit”The method depends on your hosting environment:
a. Using php.ini
Section titled “a. Using php.ini”Add or edit:
memory_limit = 256Mb. Using .htaccess
Section titled “b. Using .htaccess”Add:
php_value memory_limit 256Mc. Using .user.ini
Section titled “c. Using .user.ini”Add:
memory_limit = 256Md. Using cPanel (CageFS)
Section titled “d. Using cPanel (CageFS)”- Log in to cPanel.
- Go to Software → Select PHP Version.
- Click Switch to PHP Options.
- Locate
memory_limitand increase the value. - Save changes.
3. Check Plugins and Modules
Section titled “3. Check Plugins and Modules”- Disable unnecessary plugins or modules.
- Update outdated extensions.
- Use lightweight alternatives when possible.
4. Monitor Resource Usage
Section titled “4. Monitor Resource Usage”- Use cPanel’s resource usage tools to track memory consumption.
- Identify scripts or plugins causing spikes.