PHP 8.5: New max_memory_limit INI directive to set a ceiling memory_limit

Version8.5
TypeNew Feature

The memory_limit PHP INI directive provides a way to set the maximum memory limit a single request is permitted to consume. When this limit is exceeded, the execution is halted.

memory_limit is an INI_ALL directive, which means the directive can be changed from php.ini files, passing INI values to the PHP executable, and using ini-set function calls. Setting it to -1 removes this restriction, which allows the script to take as much memory as it needs, unless the operating system kills the process.

To provide finer control over this limit, PHP 8.5 introduces a new INI directive named max_memory_limit. It is set to -1 by default, which means this restriction is not enabled by default. max_memory_limit is an INI_SYSTEM INI directive, which means it cannot be changed at run-time.

When a max_memory_limit value is set, it becomes the largest value the memory_limit INI is allowed to set. Attempting to set a higher limit emits a warning, and sets the memory_limit to the max_memory_limit instead**.


max_memory_limit=256M
memory_limit=128M
ini_get('max_memory_limit'); // "256M";
ini_get('memory_limit'); // "128M";

When setting memory_limit at run-time, if the new value is lower than the max_memory_limit, or if the max_memory_limit is set to -1, the new memory limit takes effect.

ini_set('memory_limit', '156M'); // Allowed, lower than max_memory_limit 256M
ini_set('memory_limit', '256M'); // Allowed, equal to max_memory_limit 256M

Attempting to set a higher memory_limit or to disable it by setting memory_limit to -1 sets the memory limit to the max_memory_limit instead, and emits a warning:

ini_set('memory_limit', '300M');
Warning: Failed to set memory_limit to 314572800 bytes. Setting to max_memory_limit instead (currently: 268435456 bytes) in ... on line ...

ini_set('memory_limit', '-1');
Warning: Failed to set memory_limit to unlimited. memory_limit (currently: 268435456 bytes) cannot be set to unlimited if max_memory_limit (%d bytes) is not unlimited in ...

Backward Compatibility Impact

max_memory_limit is a new PHP INI directive, with a default value of -1, which effectively disables this limit. Setting this INI directive in older PHP versions has no effect, and does not cause any warnings or notices either.

In older PHP versions, ini_get('max_memory_limit') returns false.

On PHP 8.5 and later, PHP applications that set a memory_limit at run-time may need to check the max_memory_limit prior to setting a higher memory_limit to avoid the PHP warning.


max_memory_limit Implementation