Last active
December 28, 2020 23:05
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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