How to fix PHP Fatal error: Allowed memory size of bytes exhausted

If you work with PHP, you may come across an error message like "PHP Fatal error: Allowed memory size of bytes exhausted." This error occurs when PHP reaches its limit of memory allocated to a script. This article explains why this error occurs and how to fix it.

What Causes This Error?

By default, PHP has a memory limit of 128 megabytes (MB). When a script reaches this limit, PHP terminates the script and returns an error message. This error message indicates that PHP has exhausted the memory allocated to the script. The memory limit for PHP can be increased or decreased by editing the php.ini file.

How to Fix This Error?

There are several ways to fix this error. Some of them are:

  1. Increase the Memory Limit:

The simplest solution is to increase the memory limit for PHP. This can be done by editing the php.ini file. The following steps outline how to do this:

a. Locate the php.ini file. The location of this file varies depending on the server environment you are using. In many cases, the file is located in the root directory of your web server.

b. Open the php.ini file using a text editor.

c. Search for the line that begins with "memory_limit."

d. Change the value of this line to the new memory limit. For example, if you want to set the memory limit to 256 MB, change the line to read "memory_limit = 256M."

e. Save the changes to the php.ini file and restart the web server.

  1. Increase the Memory Limit in the Script:

If you do not have access to the php.ini file, you can increase the memory limit in the script itself. This can be done by adding the following line of code at the beginning of the script:

ini_set('memory_limit', '256M');

This code sets the memory limit for the script to 256 MB. You can change the value to the desired limit.

  1. Optimize the Script:

If the memory limit is being exhausted due to inefficient coding, you can optimize the script to use less memory. This can be done by reducing the number of variables used, removing unnecessary loops, and freeing up memory when it is no longer needed.

  1. Use cPanel MultiPHP ini Editor to Increase PHP Memory Limit:

You can log into your cPanel account of the affected website.  In the tools search, type in MultiPHP INI and click on the MultiPHP INI Editor option.

From the Basic Mode tab, select your website's domain name in the dropdown list.

Change the value in the highlighted box to reflect a higher value. Be cautious when using -1 as it will allow your account to consume all allotted memory for PHP and it may cause other tasks on your account to fail. 256M is a safe number. -1 can be used for testing.

Click on the apply button to activate the new memory limit.

Article Information
  • Article ID: 346
  • Category: Web Hosting
  • Viewed 185 times.
  • Rating:
    (0)
  • Was this article helpful?
  • Yes No
Did you find this article helpful?