đŸ¶
PHP

PHP Memory Limit Exceeded Error: How to Fix

By Filip on 10/24/2024

Learn how to fix the PHP "Allowed memory size exhausted" error and prevent your scripts from hitting memory limits.

PHP Memory Limit Exceeded Error: How to Fix

Table of Contents

Introduction

The error message "Allowed memory size of 134217728 bytes exhausted" in PHP indicates that your script is attempting to utilize more memory than your server configuration permits. This article provides a comprehensive guide to understanding and resolving this memory exhaustion issue in your PHP applications.

Step-by-Step Guide

The error "Allowed memory size of 134217728 bytes exhausted" means your PHP script is trying to use more memory than allowed. Here's how to fix it:

1. Identify the Cause:

  • Large data: Processing large files, databases, or arrays.
  • Inefficient code: Code with memory leaks or inefficient algorithms.
  • Plugin/Theme conflicts: In CMS like WordPress.

2. Increase Memory Limit:

  • php.ini: Edit the memory_limit directive.
    memory_limit = 256M
  • .htaccess (Apache): Add this line.
    php_value memory_limit 256M
  • wp-config.php (WordPress): Add this line before require_once.
    define('WP_MEMORY_LIMIT', '256M');

3. Optimize Your Code:

  • Use less memory: Process data in chunks, unset unused variables.
    unset($large_array);
  • Efficient algorithms: Use appropriate data structures and algorithms.
  • Caching: Cache results to avoid repeated computations.

4. Check for Plugin/Theme Conflicts:

  • Deactivate plugins/themes: One by one to identify the culprit.

5. Contact Hosting Provider:

  • If you can't modify settings, ask your hosting provider for help.

Important:

  • Don't set memory_limit to -1: This can lead to server instability.
  • Address the root cause: Increasing memory is a temporary fix. Optimize your code for a long-term solution.

Code Example

This code demonstrates how to troubleshoot and fix the "Allowed memory size exhausted" error in PHP. It provides examples of how to increase the memory limit in different environments (php.ini, .htaccess, wp-config.php) and offers code optimization techniques like processing data in chunks and unsetting unused variables. Additionally, it suggests checking for plugin or theme conflicts in WordPress.

This code will likely trigger the "Allowed memory size exhausted" error by attempting to create a large array:

<?php

// Attempt to create a large array
$largeArray = range(1, 10000000);

// Print the size of the array (which will likely fail)
echo "Array size: " . count($largeArray); 
?>

2. Increasing Memory Limit (php.ini):

Note: This requires access to your server's configuration files.

  1. Locate your php.ini file (often in /etc/php/ or similar).
  2. Open php.ini in a text editor.
  3. Find the line memory_limit = ... and change the value to 256M (or higher).
    memory_limit = 256M
  4. Save the php.ini file.
  5. Restart your web server (e.g., Apache or Nginx).

3. Increasing Memory Limit (.htaccess - Apache Only):

Note: This requires an Apache server and access to your website's .htaccess file.

  1. Open your .htaccess file in a text editor.
  2. Add the following line:
    php_value memory_limit 256M
  3. Save the .htaccess file.

4. Increasing Memory Limit (wp-config.php - WordPress):

Note: This is specific to WordPress websites.

  1. Open your wp-config.php file in a text editor.
  2. Add the following line before the require_once statement:
    define('WP_MEMORY_LIMIT', '256M');
  3. Save the wp-config.php file.

5. Optimizing Code:

5.1. Processing Data in Chunks:

Instead of loading a massive file all at once, process it in smaller chunks:

<?php

$handle = fopen("large_file.txt", "r");
if ($handle) {
  while (($line = fgets($handle)) !== false) {
    // Process each line individually
    echo $line . "<br>";
  }
  fclose($handle);
} else {
  echo "Error opening file.";
}

?>

5.2. Unsetting Unused Variables:

Free up memory by unsetting variables that are no longer needed:

<?php

// ... some code ...

// $largeArray is no longer needed
unset($largeArray);

// ... more code ...

?>

6. Checking for Plugin/Theme Conflicts (WordPress):

  1. Deactivate all plugins.
  2. Check if the error persists.
  3. If the error is gone, reactivate plugins one by one, testing after each activation.
  4. Repeat the process for themes if necessary.

Remember: These are just examples. The specific code and solutions will depend on your situation. Always analyze your code to identify the root cause of the memory issue and implement the most appropriate optimization techniques.

Additional Notes

Understanding Memory Allocation:

  • Bytes: Memory is measured in bytes (B), kilobytes (KB), megabytes (MB), gigabytes (GB), etc.
  • PHP Limit: The memory_limit directive in PHP sets the maximum amount of memory a single PHP script can consume.
  • Server Limit: Your server also has a finite amount of RAM. Setting memory_limit too high can lead to server instability if multiple PHP scripts try to use more memory than available.

Debugging and Troubleshooting:

  • Error Log: Check your web server's error log for more details about the error, including the specific file and line number where it occurred.
  • Memory Profiling Tools: Tools like Xdebug can help you profile your code and identify memory-intensive operations.
  • PHP Functions: Use functions like memory_get_usage() and memory_get_peak_usage() to monitor memory consumption during script execution.

Best Practices:

  • Start Small: Begin with a reasonable memory_limit increase and gradually adjust it upwards if needed, while monitoring your server's performance.
  • Code Reviews: Regularly review your code for potential memory leaks and areas for optimization.
  • Keep Software Updated: Ensure your PHP version, plugins, and themes are up-to-date to benefit from performance improvements and bug fixes.

Alternatives to Increasing Memory:

  • Database Optimization: Optimize database queries, use indexes, and consider caching mechanisms for frequently accessed data.
  • Task Queues: Offload time-consuming tasks to background processes using message queues like RabbitMQ or Beanstalkd.
  • Vertical Scaling: If optimization efforts are insufficient, consider upgrading your hosting plan to a server with more RAM and processing power.

Summary

This error means your PHP script is trying to use more memory than allowed. Here's a breakdown of the causes and solutions:

Problem Area Description Solution
Identifying the Cause
Large Data Processing large files, databases, or arrays consumes significant memory.
Inefficient Code Code with memory leaks or inefficient algorithms can exhaust memory.
Plugin/Theme Conflicts Conflicts in CMS like WordPress can lead to excessive memory usage.
Fixing the Error
Increase Memory Limit
- php.ini Edit the memory_limit directive (e.g., memory_limit = 256M).
- .htaccess (Apache) Add php_value memory_limit 256M.
- wp-config.php (WordPress) Add define('WP_MEMORY_LIMIT', '256M'); before require_once.
Optimize Your Code
- Use Less Memory Process data in chunks, unset unused variables (e.g., unset($large_array);).
- Efficient Algorithms Utilize appropriate data structures and algorithms to minimize memory footprint.
- Caching Cache results to avoid redundant computations and reduce memory usage.
Check for Plugin/Theme Conflicts
- Deactivate plugins/themes Deactivate one by one to pinpoint the source of the conflict.
Contact Hosting Provider
- Seek Assistance If unable to modify settings, contact your hosting provider for support.
Important Considerations
Avoid memory_limit = -1 Setting an unlimited memory limit can destabilize the server.
Address the Root Cause Increasing memory is a temporary fix. Optimize your code for a long-term solution.

Conclusion

In conclusion, encountering the "Allowed memory size exhausted" error in your PHP applications signifies that your script's memory consumption has exceeded the predefined limit. This comprehensive guide has equipped you with the knowledge and tools to effectively diagnose and resolve this common issue. By understanding the potential causes, such as large data processing, inefficient code, or plugin conflicts, you can strategically implement the appropriate solutions. Remember to prioritize code optimization techniques like processing data in chunks, unsetting unused variables, and employing efficient algorithms for a sustainable fix. While increasing memory limits might offer temporary relief, it's crucial to address the root cause to ensure the long-term health and performance of your PHP applications.

References

  • Allowed memory size exhausted even if correct PHP MEMORY ... Allowed memory size exhausted even if correct PHP MEMORY ... | Hi, I use Nextcloud 24.0.5 on my vserver with Plesk. I set the following parameter in PHP Version: 8.0.24 Speicherlimit: 512 MB Maximale AusfĂŒhrungszeit: 3600 Maximale GrĂ¶ĂŸe zum Hochladen: 20 MB But I will get the following message PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8408552 bytes) in nc/apps/maps/lib/Helper/ExifGeoData.php on line 120 Also I can’t update with the online updater because I will get the same error. What have I to do to avoid...
  • php - Allowed memory size of 134217728 bytes exhausted (tried to ... php - Allowed memory size of 134217728 bytes exhausted (tried to ... | Jul 3, 2018 ... I have a problem with Laravel . after restart my system, My project will not run !!! I run with php artisan serv , but I have below messages in ...
  • Troubleshooting the “PHP Fatal error: Allowed memory size ... Troubleshooting the “PHP Fatal error: Allowed memory size ... | The “allowed memory size exhausted” fatal PHP error means that a PHP script exceeded the set PHP memory limit and thus failed. This can result in 500 errors or broken functionality within a webpage.
  • Matomo Migration error "Fatal error: Allowed memory size of ... Matomo Migration error "Fatal error: Allowed memory size of ... | I’m moving one Matomo instance to another. Once I ironed out the kinks, everything worked well for the smaller sites with only a few thousand visits. But now I’m trying to move a site that has ~25,000 visits, and getting the following error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 163840 bytes) in /home/public/stats/matomo/plugins/Migration/Migrations/LogMigration.php on line 89 ERROR [2021-06-09 22:10:23] 95343 Fatal error encountered: /home/public/sta...
  • Fatal error: Allowed memory size of 134217728 bytes exhausted ... Fatal error: Allowed memory size of 134217728 bytes exhausted ... | Hi, After clearing the cache I get the following error in the Drupal admin: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 5916022 bytes) in /var/www/includes/theme.inc on line 1413 I increased the php memory limit to 128M which should be more then enough according to the information I found on the internet. I'm using the views and Drupal for Firebug module. When I disable the Drupal for Firebug module the error disappears.
  • Unable to allocate more memory to PHP in order to avoid "PHP Fatal ... Unable to allocate more memory to PHP in order to avoid "PHP Fatal ... | I have imported several years of data from Google Analytics into my Matomo instance, and upon attempting to view a multi-year range of Visits Over Time, I am...
  • Problem with Artisan: Allowed memory size of 134217728 bytes ... Problem with Artisan: Allowed memory size of 134217728 bytes ... | ... error when running any Artisan or Composer command: Copy PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 118784 bytes).
  • X theme - Fatal error: Allowed memory size of 134217728 bytes ... X theme - Fatal error: Allowed memory size of 134217728 bytes ... | Hi |I installed the theme and am getting this error now? Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 786432 bytes) in /home/admindst/public_html/wp-content/themes/x/framework/functions/plugins/visual-composer.php on line 2879
  • Moodle in English: Allowed memory size of 134217728 bytes ... Moodle in English: Allowed memory size of 134217728 bytes ... | 134217728 bytes is actually 128 megabytes, which is a new default in PHP 5.2. I got the same message also "here and there" under my Windows box in Moodle 1.8.

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
đŸ€źClickbait