Increase PHP memory limit

PHP scripts are only allocated a certain amount of memory that it can use, and whet it reaches the limit, it will produce the following error;

PHP Fatal error: Allowed memory size of xxxx bytes exhausted (tried to allocate yyyy) in yourscript.php

To fix this, you'll need to increase the memory limit for PHP scripts using any of the following methods;

Modifying PHP global configuration file (php.ini)

Changing the setting in the global configuration will affect all scripts run in the system.

Inside the file, search for the following line;

; Maximum amount of memory a script may consume (128MB)
memory_limit = 128MB

Change the value (in Megabyte) and restart Apache for the setting to take effect.

Configure .htaccess

To make the setting effective only to a certain folder (or project), you can use the .htaccess file to do the trick. To do this locate (or create) .htaccess file in your PHP scripts folder and add the following line;

php_value memory_limit 128MB

Within PHP script

This is probably the best method as the setting applies only to the particular script, and would not allow other poorly written scripts to also consume and waste the system's memory.

To do this, add the following line in your PHP script;

ini_set('memory_limit', '128MB');

Sign up for Object Oriented PHP & MVC and many other great courses on Udemy to learn more.

Written by Mohd Shakir Zakaria. Last updated on 2019-02-12