PHP: Increase PHP Memory Limit in htaccess, apache or in a php script

Most of us have come across this error: “Fatal error: Allowed memory size of xxxxxx bytes exhausted (tried to allocate yyy bytes) in ….” in the php error logs.

In php, running out of memory in usually a sign that your php script is not too well written or has a bug or two in it; However sometimes even the best of our php scripts still require more memory than usual especially if it is handling large amounts of data.

Luckily in php, increasing the memory limit is an easy task to do and can be done in a number of ways.

Setting PHP Memory Limit inside PHP Script

Inside your php script that requires the increase in memory, you can add the following line which increases the memory limit just for that page. So putting this at the top of the script can help you handle larger amounts of data.

[php toolbar=”true” classname=”one_line”]

// note that memory_limit is case sensitive!
ini_set(‘memory_limit’,’64M’);
// rest of your code follows

[/php]

Setting PHP Memory Limit in .htaccess

Setting a memory limit in .htaccess is also straight forward. Add a line into your .htaccess file. Note that this will affect any php files within that folder and subfolders.

[php toolbar=”false” classname=”one_line”]php_value memory_limit 64M[/php]

Setting PHP Memory Limit in php.ini config file

If you want to set the memory limit within PHP itself, then edit the php.ini file which is usually found under /etc/php/apache2/php.ini under Debian and find the line shown below and change it to whatever you need. This will affect all php scripts running under your server so be careful with this value.
Note: you will have to restart apache for this change to take effect

[php toolbar=”false” classname=”one_line”]memory_limit = 64M[/php]

Setting PHP Memory Limit in Apache

Inside apache, find the virtual host that needs the increase in memory limit and add the line as shown below in italics.
Note: you will have to restart apache for this change to take effect

[php toolbar=”true” classname=”one_line”]

<VirtualHost *:80>
# apache settings for virtual host
php_value memory_limit 64M
# other settings etc. follow as usual.
</VirtualHost>

[/php]

Leave A Comment