Checking memory_limit in PHP


The ‘memory_limit’ is the maximum amount of server memory that a single PHP script is allowed to use. The value needs to be converted before comparing the threshold of memory.

For example − 64M is converted to 64 * 1024 * 1024. After this, the comparison is done and the result is printed out.

<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
   if ($matches[2] == 'M') {
      $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
   } else if ($matches[2] == 'K') {
      $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
   }
}
$ok = ($memory_limit >= 640 * 1024 * 1024); // at least 64M?
echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';

The output will be the memory limit of that specific environment setup.

Updated on: 07-Apr-2020

942 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements