If you have seen an error like “Fatal Error: __PHP Allowed Memory Size Exhausted” in apache logs or in your browser, this means that PHP has exhausted the maximum memory limit. This post will show 3 different ways on how you can increase the php memory limit and also explain when you should use them.
First, let’s see where is this limit coming from. Normally you will see from the error message what is the actual limit, as this will look like:
The default value might differ depending on what php version and linux distribution you are running, but normally this will be set to either 8M or 16M. For example on my debian etch, running on php 5.2 this is set by default at 16M.
In order to identify the current value on your system, look inside your php.ini and search for memory_limit:
There are three ways to change this value, the obvious way – changing the global value from php.ini, but also an individual method to change it just for a script, or folder.
1. Changing memory_limit globally from php.ini
This is the simplest and most obvious method. You just edit your php.ini and change the memory_limit to whatever you need. For ex:
You will require access to make changes to php.ini on the system. This change is global and will be used by all php scripts running on the system. Once you change this value, you will need to restart the web server in order for it to become active.
Keep in mind that this limit has its logic and don’t increase it artificially, as poorly written php scripts might overkill your system without proper limits. Note: if you know what you are doing and want to remove the memory limit, you would set this value to -1.
2. Changing memory_limit using .htaccess for a single folder/vhost
Changing the global memory_limit might not be a good idea, and you might be better changing this only inside one folder (normally one application or virtual host) that needs this value changed for its functionality. To do this you have to add to the respective location .htaccess something like:
This change will be local only, and can be useful for webmasters that don’t have control on the system php.ini. This change would not require a reload and will become active immediately.
3. Changing memory_limit inside a single php script.
For even more control you can set this directive inside a single php script. To do so you would use in your code:
The advantage of this method is that you have more control and set this value just where you know it is really needed. Also it can be done without having access to the system php.ini, and will become active immediately.
Note: in order to be able to use these PHP resource limits, your PHP version must have been compiled with the —enable-memory-limit configure option. Normally most packed versions will have this, but just in case if this doesnâ€™t work for you as expected, check on how php was compiled first.