The PHP Memory Limit Error occurs when a script attempts to allocate more memory than the limit set in the php.ini
configuration file. If the memory requirement exceeds the allowed amount, PHP will throw a Fatal Error similar to this:
Error Message:
codeFatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in /path/to/script.php on line 42
This error usually indicates that either:
- You are running a memory-intensive script.
- The memory limit configured in
php.ini
is too low.
Fix the PHP Memory Limit Error
You can resolve this error by increasing the PHP memory limit. Below are different ways to fix this:
Temporary Fix (Directly in Code)
Use the ini_set()
function at the top of your PHP script to temporarily increase the memory limit.
code<?php
// Increase memory limit to 256M for the current script
ini_set('memory_limit', '256M');
// Your script logic here
echo "Memory limit increased to 256MB.";
This change only affects the specific script during its execution and does not modify the server-wide configuration.
Modify the php.ini
Configuration
If you have access to the server, locate the php.ini
file and increase the memory limit.
- Open your
php.ini
file. - Look for the following line: code
memory_limit = 128M
- Increase it to a higher value, such as: code
memory_limit = 256M
- Restart your web server (e.g., Apache or Nginx) for the changes to take effect:
- Apache:
sudo service apache2 restart
- Nginx:
sudo service nginx restart
- Apache:
Use .htaccess
(For Apache Servers)
If you don’t have access to php.ini
, you can add the following line to your .htaccess
file to increase the memory limit for your site.
codephp_value memory_limit 256M
Use WordPress-Specific Method (If Using WordPress)
If you are working with WordPress, you can increase the memory limit by adding the following line to your wp-config.php
file:
codedefine('WP_MEMORY_LIMIT', '256M');
These methods ensure that your PHP scripts have enough memory to run without exhausting the limit. Choose the one that best fits your situation, ensuring you have permission to make these changes on your server.