Skip to main content

PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes)

If you started running into this error after updating your PHP version, you can use the following steps to resolve it.  

 

Method 1 - Updating php.ini Config (Debian/Ubuntu)

We found that the permanent solution to this issue is to update the memory_limit value in the php.ini config file. 

Run the following command to edit the php cli config file. 

Change the php version in the command to match the version you have enabled.  (Use php -v to see current version)

sudo nano /etc/php/7.4/cli/php.ini

Locate the memory_limit line and make sure the value ends in not MB

image-1617428038467.png

Explanation

In our testing it seemed that PHP versions prior to PHP 7.4 allowed the memory limit to end in MB but in recent versions it needs to end in M.  Besides that you may have to increase this value to meet your needs, typically you can start with 64M and gradually increase if needed.  Many high end web servers run fine at 256M or 512M.  


Method 2 - Set Memory Limit in the Command

Instead of changing the memory limit in the php.ini config file, you can also tell PHP CLI to use a specific amount of memory in the command you're trying to run.  In the PHP command you're trying to run, add -d memory_limit=512M right after the PHP.  This will set the memory limit for that one line command.  This method isn't idea because you have to add these values every time you run a command, however, it is good if you can't modify the php.ini file. 

Example

sudo -u www-data php -d memory_limit=512M artisan schedule:run 

Method 3 - Change PHP Version

If this issue was caused after updating PHP then you could just try downgrading your PHP version, run the commands again, and then putting your PHP version back.  To be honest, this is what we did until we figured out Methods 1 & 2.  Removing the B in MB from our config file fixed the issue immediately.  


Method 4 - Don't do this! 

Some people on the internet suggested setting your PHP memory_limit value to -1 to fix this issue.  This will fix your issue, however, don't do it as a permanent solution.  Setting your memory limit to -1 means the PHP CLI can get overloaded and eat up all your memory, which could crash your server or at least the process.   You're best bet is to use Method 1 and don't over provision, meaning don't set your memory_limit to a value greater than the amount of memory(ram) you have on the server.