The memory_limit directive in PHP controls the maximum amount of memory a script is allowed to use. When set to -1, it means there is no memory limit, and scripts can use as much memory as the system allows.

Checking the Current memory_limit

To check your PHP memory limit, run:

<?php
echo ini_get('memory_limit');
?>

Or use the command line:

php -r "echo ini_get('memory_limit');"

Setting memory_limit = -1

If you need to remove the memory limit for PHP scripts, you can do it in multiple ways:

Modify php.ini (Recommended for Permanent Change)

1

Open the php.ini file

nano /etc/php.ini # For CentOS/RHEL
nano /etc/php/7.x/apache2/php.ini # For Ubuntu/Debian
2

Find the line

memory_limit = 128M
3

Change it to

memory_limit = -1
4

Save and exit (Ctrl + X, then Y)

5

Restart the web server

systemctl restart apache2 # For Apache
systemctl restart nginx # For Nginx

Modify .htaccess (For Shared Hosting)

If you do not have access to php.ini, add this line to your .htaccess file:

php_value memory_limit -1

Change via ini_set() in PHP Script (For Specific Scripts)

To allow unlimited memory usage for a single script:

<?php
ini_set('memory_limit', '-1');
?>

Set via Command Line (For CLI Scripts)

To run a script with no memory limit:

php -d memory_limit=-1 script.php

Should You Use memory_limit = -1?

When It Is Useful:

  • Running memory-intensive scripts (e.g., large database exports, image processing, AI models).
  • Debugging memory allocation issues.

Why It Can Be Dangerous:

  • Can crash the server by consuming all available RAM.
  • May lead to out-of-memory (OOM) errors if a script has memory leaks.
  • Not recommended on shared hosting (affects all users).

Best Practice: Increase the Limit Instead

Instead of removing the limit, increase it to a reasonable value:

memory_limit = 512M # or 1G for large applications

For a temporary increase in a script:

ini_set('memory_limit', '512M');

How to Monitor PHP Memory Usage

Use this to track memory usage in your script:

echo "Memory used: " . (memory_get_usage(true) / 1024 / 1024) . " MB";
  • memory_limit = -1 removes all restrictions, but it is risky.
  • Use it only for debugging or CLI scripts.
  • Instead of removing limits, increase memory to a safe value (512M, 1G).
  • Monitor memory usage to avoid crashes.