Here is how to increase the PHP memory limit and avoid crashing your web applications using anyone of the three convenient ways.
Generally, PHP scripts are only allowed to use a certain amount of memory per request. This is for good reason. It prevents rogue or badly written scripts from gobbling up all the available memory on a server and wreaking havoc on other services and applications running on the same server.
There are times when a script may require more memory than that which has been allocated by the server admin. This is easy to detect as the webserver error logs should print out a line similar to this:
PHP Fatal error: Allowed memory size of x bytes exhausted (tried to allocate x) in yourscript.php
Where x is the amount in bytes your PHP tried to allocate.
To fix this issue you need to increase the PHP memory limit. There are three main ways to do it.
- Via the PHP configuration file (php.ini)
- Via the web server .htaccess file
- At the Start of your PHP script via the ini_set() function
Increase PHP Memory Limit via php.ini file
This method will affect all scripts running in the affected system. You will need to open the file with your favorite text editor and find the line that looks similar to this:
memory_limit = 16M
The location of the php.ini
file really depends on the Operating System and in some cases the version number.
Check out this guide on PHP configuration files for details
Increase the limit in Megabytes (M). The amount you set for the limit really depends on the applications you are running on the server.
You then need to restart the webserver for the changes to take effect.
Check out this guide on how to start, stop, and restart the Apache service
Using the web Server .htaccess File
This method allows you to increase the memory limit at folder scope. This can be achieved using the .htaccess file. You can add the following line to an existing .htaccess file or create one using a text editor.
php_value memory_limit 256MB
The above directive will apply to the current folder and all child folders.
Using the the ini_set() function
There are many cases where it may not be advisable to increase the PHP memory limit server-wide nor folder-wide. This method allows you to increase the memory limit just for the script that needs it.
All you need to do is add the following line to your PHP script preferably at the top.
ini_set('memory_limit', '256MB');
That should be localized to the current script.
There you have it. Three ways with their use-cases show you how you should increase PHP memory limit and in what contexts.
Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.