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:
It will return something like:
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:
phpinfo();
?>
Look for "Loaded Configuration File" in the output.
Modify php.ini to Set memory_limit = -1
Open php.ini with a text editor
Find the line
or
Change it to
Save and exit
Press Ctrl + X, then Y, then Enter.
Restart PHP and Web Server
For Apache:
For Nginx with PHP-FPM:
sudo systemctl restart nginx
For cPanel (if applicable):
Verify the Change
Run:
Expected output:
Alternatively, create a PHP file:
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:
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:
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 = 1G
- Edit php.ini, set memory_limit = -1.
- Restart Apache/Nginx.
- Verify using php -i | grep memory_limit.
- Consider alternatives like .htaccess or ini_set() if needed.
- Use unlimited memory only when necessary to prevent crashes.


