Home » Php » php – How to intentionally cause a "Fatal error: Allowed memory size of xxx bytes exhausted"

php – How to intentionally cause a "Fatal error: Allowed memory size of xxx bytes exhausted"

Posted by: admin July 12, 2020 Leave a comment

Questions:

Whenever I’ve received this error, I just increased the memory to fix it. I have a case where, for testing purposes, I want to cause a page to use up all the memory however big I set the memory_limit.

I have no idea how to go about doing that.

EDIT:
I tried this:

<?php
echo "start";
@ini_set('memory_limit', '1M');
$test = "a";
while (1) {
    $test = "a" + $test;    
}
echo "done";
?>

But it didn’t crash. At the end it just printed “startstart” which is strange that it was printed twice…

I’d like a simple code example, the “put a lot of stuff in memory”.. well I know that much.

How to&Answers:

Here’s the problem:

$test = "a" + $test;

+ in PHP is for arithmetic, not string concatination. Use:

$test = "a" . $test;

Answer:

Should eat all memory.

$a = 'x';
while (true) {
    $a = $a.$a;
}

Answer:

str_pad("",PHP_INT_MAX);

Answer:

You can do an infinite loop, although I would advise against that.

You can also open / read into memory big files that would exceed the memory limit, you could also write a loop that would generate a string with the amount of bytes which would exceed the memory limit.

Which is best, no clue. But there are a couple options available to you.

Answer:

  1. Download all Google Maps images.
  2. Then re-size them using GD into a 1-1 scale.

Answer:

Write a PHP function that tries to find a pattern within /dev/random

Answer:

<?php
$limit = ini_get('memory_limit');
$last = strtolower($limit[strlen($limit)-1]);
switch($last) {
    case 'g':
        $limit *= 1024;
    case 'm':
        $limit *= 1024;
    case 'k':
        $limit *= 1024;
}
$limit = $limit + 1;//not needed actually, I assume the script has consumed 1 byte of memory by now...
$foo = `dd if=/dev/zero bs=$limit count=1`;
//or, if you don't like the command line:
$bar = str_repeat($a,$limit);