PHP Increase Memory Limit Using Htaccess, Apache Or PHP

Overview

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 log files.

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. It could also be caused by script that have to process large amounts of data at once. Sometime even well designed php scripts still require more memory than usual especially if it is handling large amounts of data or when trying to read large files into memory.

PHP Increase Memory Limit Using Htaccess, Apache Or PHP Script

Luckily in php, increasing the memory limit is an easy task to do and can be done in a number of ways. Below I will show you how to increase (or even decrease) the memory limit using either htaccess, apache and even inside the php script itself.

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

// note that memory_limit is case sensitive!
ini_set('memory_limit','64M');

// rest of your code follows

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. You won’t need to restart apache when updating the htaccess. Be careful as any typo’s in the htaccess file will prevent the website from loading correctly.

php_value memory_limit 64M

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

memory_limit = 64M

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

<VirtualHost *:80>

# apache settings for virtual host

php_value memory_limit 64M

# other settings etc. follow as usual.

</VirtualHost>

Conclusion

Needing more memory for a php script can be frustrating, luckily you are able to increase the php memory limit for your website or just a specific subfolder of your site. It is easy to increase the limit using either htaccess, apache or within the php script.