Skip to content

Instantly share code, notes, and snippets.

@BenMorel
Last active December 28, 2020 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenMorel/1daae4597dc97a8eb6d2e868a9984bfd to your computer and use it in GitHub Desktop.
Save BenMorel/1daae4597dc97a8eb6d2e868a9984bfd to your computer and use it in GitHub Desktop.
Increases PHP memory limit. Keeps the current setting if the current limit is large enough.
<?php
function _parse_memory_limit(string $value): int
{
if (preg_match('/^([0-9]+)([KMG]?)$/', strtoupper($value), $matches) !== 1) {
throw new RuntimeException('Invalid value for memory_limit: ' . $value);
}
[, $number, $multiplier] = $matches;
$number = (int) $number;
if ($multiplier !== '') {
$pos = strpos('KMG', $multiplier);
$number *= 1024 ** ($pos + 1);
}
return $number;
}
function increase_memory_limit(string $value): void
{
$current = ini_get('memory_limit');
if ($current === '-1') {
// already unlimited
return;
}
if ($value === '-1') {
// set to unlimited
ini_set('memory_limit', '-1');
return;
}
$currentInt = _parse_memory_limit($current);
$valueInt = _parse_memory_limit($value);
if ($valueInt > $currentInt) {
ini_set('memory_limit', $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment