PHP scripts are only allocated a set amount of memory that it can use and will exit and throw the following error once it reaches the limit;

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

You'll need to increase the memory limit for PHP scripts to avoid the above error using some of the available methods.

Increase PHP memory limit via file (php.ini)

This method will apply to all the PHP scripts that run in the system. It is a good method to follow if you're not hosting multiple systems in a single host.

  1. Open PHP configuration file using your preferred text editor.
    $ sudo vi /etc/php/7.2/apache2/php.ini
  2. Search for memory_limit directive within the configuration file.
    ; Maximum amount of memory a script may consume (128MB)
    ; http://php.net/memory-limit
    memory_limit = 128MB
  3. Set the memory limit value with appropriate unit.
    ; Maximum amount of memory a script may consume (128MB)
    ; http://php.net/memory-limit
    memory_limit = 512MB
  4. Restart your web server for the changes to take effect.

Increase PHP memory limit via .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 512MB

Increase PHP memory limit via ini_set() function

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', '512MB');

Increase PHP memory limit for cPanel

You don't have access to PHP's configuration file if you're hosting your system in cPanel, but cPanel do provide the option to change the setting from its admin dashboard.

Share this guide!
Discuss the article:

Comment anonymously. Login not required.

Share!