Increase PHP memory limit

Increase PHP memory limit - Allowed memory size exceeded

To every PHP script that is executed it is assigned a limited amount of physical memory that can be used. For that reason, sometimes you need to increase PHP memory limit. For example, in my php.ini configuration file is set that every script can use up to 2MB of memory. So, if my PHP script needs more than 2MB memory, even a single byte, it will produce an error similar to this one:

Fatal error: Allowed memory size of x bytes exhausted (tried to allocate x bytes) in

Why is there a memory limit?

This limitation is set for security reason. If there was no limitation the script can eat the whole physical memory.

How to fix it?

There are 3 ways to increase the memory limit:

Increase PHP memory limit through the php.ini configuration file

In Ubuntu, php.ini file can be located under /etc/php5/ directory. Open the file and search for the "memory_limit" directive. It should look something like this:

; Maximum amount of memory a script may consume (2MB)
memory_limit = 2M

Adjust it for your needs and restart the web server to reload the new settings, using one of the following commands:

#service apache2 restart
#/etc/init.d/apache2 restart 
Note: If you increase the memory limit this way, every single script will have this limit.

Increase PHP memory limit through your PHP script

Another way to extend the memory limit is by using the ini_set function.

ini_set('memory_limit', 16M);

Just copy and paste the code at the top of the script that needs more memory and you are good to go. No need to restart the web server. Every time your script is executed PHP will reserve 16MB memory for it.

Increase PHP memory limit through .htaccess

If you don't have .htaccess file, you can create it in your root directory of your website and add the following line:

php_value memory_limit 8M;
Note: This method will only work if PHP is executed as an apache module.
You don't know which way to use it?

My suggestion is to use the second way and use it only in the script that really needs more memory.

- Posted by Eva to Php