How to modify PHP memory limit

PHP has a memory limit configuration that determines the maximum amount of memory a single PHP script can consume.

This memory_limit is usually defined in a php.ini file as follows:

memory_limit = 128M

The default memory_limit configuration for PHP is 128M or 128 Megabytes. You can replace this value in your php.ini file with any other int value.

Without the M symbol, the limit will be measured in bytes:

; 👇 limit to 256 Megabytes
memory_limit = 256000000

; 👇 this is the same
memory_limit = 256M

The memory limit in PHP is calculated on a pre-script basis, meaning that each PHP script request is independent of the other.

For example, if you have 3 running PHP scripts where each consumes 90MB of memory, then the total memory used by PHP will be 270MB passing the 128MB limit.

When you have a single PHP script that consumes 200MB of memory, then PHP will throw an Out of memory fatal error.

To remove the memory_limit, you can set the value as -1 like this:

memory_limit = -1

This way, PHP won’t have memory limitations and can consume all available memory on your server.

Aside from editing the php.ini file, you can also edit the .htaccess file as shown below:

php_value memory_limit 256M

You can get the current memory_limit value with the ini_get() function:

echo ini_get("memory_limit"); //128M

You can also change the memory limit configuration only for a specific script using ini_set() function:

// 👇 set memory limit as 256M using ini_set()

echo ini_set("memory_limit", "256M");

And that’s how you set the memory_limit configuration in PHP.

If you’re using editing the memory_limit for a WordPress site, keep in mind that WordPress has its own memory constants defined as:

  • WP_MEMORY_LIMIT sets the memory limit in WP frontend area
  • WP_MAX_MEMORY_LIMIT sets the memory limit in WP administration area

The WP_MEMORY_LIMIT is usually set at 64MB for WP multisite and 40MB for a single site, while WP_MAX_MEMORY_LIMIT is usually set at 256MB.

You can define these constants in wp-config.php file, below the WP_DEBUG definition as shown below:

define( 'WP_DEBUG', true );

/* Add any custom values between this line and the "stop editing" line. */
define( 'WP_MEMORY_LIMIT', '300M' );
define( 'WP_MAX_MEMORY_LIMIT', '300M' );

WordPress configuration doesn’t override the PHP configuration, so make sure you have memory_limit at 300MB or more when you set WP_MEMORY_LIMIT and WP_MAX_MEMORY_LIMIT at 300MB.

That’s all you need to change for a WordPress site.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.