When a PHP script runs out of memory, it usually stops with an error saying that the allowed memory size has been exhausted. This happens when a script tries to process large data, handle file uploads, or perform heavy operations like image processing. To avoid this issue, PHP allows you to increase the memory limit for a specific script.
This guide explains what the PHP memory limit is and how you can increase it safely for an individual script.
What Is memory_limit in PHP?
memory_limit is a PHP configuration setting that defines the maximum amount of memory a PHP script is allowed to use while it is running. Once the script reaches this limit, PHP stops execution to protect the server from excessive resource usage.
By default, many servers set this value between 64MB and 128MB, which may not be enough for memory-intensive tasks.
Increase memory_limit Using ini_set()
The easiest way to increase the memory limit for a single script is by using the ini_set() function inside the PHP file.
Add the following line immediately after the opening PHP tag:
How this works
-
The new memory limit applies only to that script
-
Other PHP files on the server are not affected
-
The change lasts only while the script is running
When to use this method
-
Large database queries
-
Import or export operations
-
Image or video processing
-
Backup and migration scripts
Increase memory_limit Using a Custom php.ini File
If you want to increase the memory limit for all scripts under a specific user or directory, you can create a custom php.ini file.
Create a file named php.ini in the document root and add:
-
Applies to all PHP scripts in that directory
-
Useful for shared hosting environments
-
Provides a more permanent configuration
This method is recommended when ini_set() is disabled by the server administrator.
Increase memory_limit Using .htaccess
On servers running Apache with mod_php, you can set the memory limit using the .htaccess file.
Add the following line to the .htaccess file:
Important notes
-
Works only on Apache servers using mod_php
-
Does not work with PHP-FPM or CGI
-
May cause a 500 Internal Server Error if unsupported
Which Method Should You Choose?
-
Use ini_set() if you want to increase memory for one specific script
-
Use php.ini if you need a directory-level or user-level change
-
Use .htaccess only if your server supports it
Check the Current Memory Limit
To confirm the current memory limit, use the following code:
<?php echo ini_get(“memory_limit”);
Increasing the memory limit can help scripts run successfully, but it should be done carefully. If a script frequently needs more memory, it may indicate inefficient code that should be optimized.
Adjust memory limits responsibly to maintain server stability and performance.
If you require help, contact SupportPRO Server Admin
