PHP Memory Limit and htaccess

The PHP memory limit will need to changed sooner or later as we start writing and running more resource intensive scripts. The idea of a memory limit is important on a web server since the server may be serving many requests at a given time, and we wouldn't want any one request or script consuming too many resources. Also, it is useful to limit how much memory a script can consume in a setting (like a VPS) where resources like RAM are limited.

There are 3 main ways of setting the PHP memory limit. Two of them involve using php.ini files and the other involves using an htaccess file. The method you will use is determined by the type of setup you are under and what your requirements are.

Using the main php.ini file

This is the approach which should be taken if you want to enforce a global memory limit across all PHP scripts and websites served by the PHP interpreter. You can only use this method if you have access to the server's php.ini file and thus is only available on VPS and dedicated servers.

Locate the php.ini file which is at /etc/php5/apache2/php.ini on newer Ubuntu/Debian systems. Alternatively, you can use the PHP function phpinfo() to tell you where this configuration file is located.

Look for and change the line which starts with memory_limit like so:

memory_limit = 96M

Replace 96 with the number of megabytes you want to set the limit to. Restart Apache for the changes to take effect.

Using an htaccess file

This approach is to be used if you don't have access to your server's main PHP configuration file or if you want to enforce different memory limits for PHP scripts in different directories.

This method will only work if PHP is running as an Apache module.

Add the following line to the/an htaccess file in the directory you want to affect, or the web root to affect a whole website.

php_value memory_limit 96M

Once again, replace 96 with the number of megabytes you want to set the limit to. These changes should take effect immediately.

Using a php.ini file in the web root

This approach is to be used if you don't have access to your server's main PHP configuration file.

This method will only work if PHP is running as CGI/Fast CGI.

Add the following line to a/the php.ini file in the web root.

memory_limit = 96M

Remember to replace 96 with the number of megabytes you want to set the limit to.

Shared hosting

If you are on shared hosting, you may not have the option to change the PHP memory limit at all. Confirm this with your hosting provider. If this is the case, you may want to consider changing service providers.

Confirm your changes

You can use the phpinfo() function to determine if the memory limit has been changed correctly.

We hope this tutorial was useful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...