PHP Fatal error: Allowed Memory Size of 20971520 Bytes exhausted (tried to allocate 131072 bytes) Error and Solution

The “Allowed Memory Size” error message in PHP indicates that the script has exhausted the memory limit allocated to it by the PHP configuration. The default memory limit for PHP scripts is 128MB, but this value can be increased or decreased depending on your server configuration. (www.ebsta.com)

When you see an error message like “Allowed Memory Size of xxx Bytes exhausted”, it means that the script tried to allocate more memory than the allowed limit. The number after “Allowed Memory Size of” represents the memory limit in bytes that was exceeded, and the number after “tried to allocate” represents the amount of memory that the script was trying to allocate when it ran out of memory.

To resolve this error, you can try the following solutions:

  1. Increase the memory limit: You can increase the memory limit for PHP scripts by modifying the memory_limit directive in the php.ini file. If you don’t have access to the php.ini file, you can also try setting the memory limit using the ini_set() function in your PHP script.

For example, to set the memory limit to 256MB, you can add the following line to your PHP script:

ini_set('memory_limit', '256M');
  1. Optimize your code: If increasing the memory limit is not an option, you can try optimizing your code to use less memory. This can involve reducing the size of data structures, using more efficient algorithms, or freeing up memory when it is no longer needed.
  2. Use unset() function to free up memory: If your code involves processing large data sets or working with large files, it can be helpful to use the unset() function to free up memory as you go. This function removes the variable from memory and releases the memory that was allocated to it.

For example, if you have a large array called $data, you can use the unset() function to free up the memory when you are done with it:

unset($data);

By implementing one or more of these solutions, you should be able to resolve the “Allowed Memory Size” error in your PHP script.

Leave a Comment