How to test PHPs memory_limit setting

0 minutes, 42 seconds

So, we all know that in PHP, you configure it with a php.ini file. And in there, you can set the amount of RAM a script can use with the memory_limitsetting (remember this is “M” not “MB”!).  And if you get this error:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 234881025 bytes)

Then you can increase the memory_limit to be larger (don’t forget to restart apache!). However, what if you want a script to hit that limit to see how your error logs and such are set up?  I had more fun than I thought I would writing a textbook solution to a textbook problem.  Here it is in it’s 4 line glory:

$str = 'memory!';
$i = 1;
while ($i++ != 100) $str .= $str  ;
print "done!";

When you run this you should see an error as this will exceed 128M of memory. If not, so salt to taste ($i++ != 200) if you run with a higher memory_limit setting!

4 thoughts on “How to test PHPs memory_limit setting

    1. mrjones Post author

      Oh, awesome! Assign a variable that is the size of memory_limit and it will inherently exceed that size. Neat!

      However, When I run it in a full LAMP stack, I get an error:

      PHP Error 8:

      Message:
      A non well formed numeric value encountered
      in /vagrant/application/views/_layout/header.php:1

      Reply
      1. Firebus

        Oh yah, derp, because you can use shorthand notation like ‘128M’ and that’s what gets returned literally by ini_get(). No conversion is done for you.

        I initially misremebered there being a built-in to convert, but I must have been remembering the discussion here: http://php.net/manual/en/function.ini-get.php#refsect1-function.ini-get-examples

        So, easy enough to use ini_get(‘memory_limit’) but not as easy to one-liner. Also memory_limit has a special value of -1 for unlimited that should be handled (in that case you’d want to get the total memory installed on the server and pad a string that far? :)

        This would be better as a little module: https://gist.github.com/firebus/2e324b1261f0e2cbe1f9

        I’m afraid to run it with memory_limit set to -1…

        Reply

Leave a Reply to mrjones Cancel reply

Your email address will not be published. Required fields are marked *