The memory_limit directive in PHP controls the maximum amount of memory a script can use. Setting it to -1 removes all memory restrictions, allowing PHP scripts to use as much RAM as needed.

Locate the php.ini File

To modify php.ini, you first need to locate it.

Check Current PHP Configuration

Run this command:

php --ini

It will return something like:

Configuration File (php.ini) Path: /etc/php/7.4/apache2
Loaded Configuration File: /etc/php/7.4/apache2/php.ini

This tells you the correct php.ini file to edit.

Alternatively, create a PHP script:

<?php
phpinfo();
?>

Look for "Loaded Configuration File" in the output.

Modify php.ini to Set memory_limit = -1

1

Open php.ini with a text editor

sudo nano /etc/php/7.4/apache2/php.ini # Ubuntu/Debian (Apache)
sudo nano /etc/php/7.4/cli/php.ini # Ubuntu/Debian (CLI)
sudo nano /etc/php.ini # CentOS/RHEL
2

Find the line

memory_limit = 128M

or

memory_limit = 512M
3

Change it to

memory_limit = -1
4

Save and exit

Press Ctrl + X, then Y, then Enter.

Restart PHP and Web Server

For Apache:

sudo systemctl restart apache2

For Nginx with PHP-FPM:

sudo systemctl restart php7.4-fpm
sudo systemctl restart nginx

For cPanel (if applicable):

service httpd restart

Verify the Change

Run:

php -i | grep memory_limit

Expected output:

memory_limit => -1 => -1

Alternatively, create a PHP file:

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

Visit the page in your browser and check if it returns -1.

Alternative: Modify .htaccess (For Shared Hosting)

If you cannot edit php.ini, try adding this to .htaccess:

php_value memory_limit -1

Then restart your web server.

Alternative: Modify via ini_set() (For Specific Scripts)

If you only want to remove memory limits for a specific PHP script, use:

ini_set('memory_limit', '-1');

Warnings & Best Practices

When to Use memory_limit = -1:

  • Running memory-heavy scripts (e.g., image processing, database exports, large file processing).
  • Debugging memory allocation issues.

When Not to Use memory_limit = -1:

  • On shared hosting (may crash other users websites).
  • In production without monitoring (can cause server crashes).

Alternative:

Instead of unlimited memory, set a high but safe value, e.g.:

memory_limit = 512M
memory_limit = 1G
  1. Edit php.ini, set memory_limit = -1.
  2. Restart Apache/Nginx.
  3. Verify using php -i | grep memory_limit.
  4. Consider alternatives like .htaccess or ini_set() if needed.
  5. Use unlimited memory only when necessary to prevent crashes.