phpmemory-limit

checking memory_limit in PHP


I'm need to check if memory_limit is at least 64M in my script installer. This is just part of PHP code that should work, but probably due to this "M" it's not reading properly the value. How to fix this ?

  //memory_limit
    echo "<phpmem>";
    if(key_exists('PHP Core', $phpinfo))
    {
        if(key_exists('memory_limit', $phpinfo['PHP Core']))
        {
            $t=explode(".", $phpinfo['PHP Core']['memory_limit']);
            if($t[0]>=64)
                $ok=1;
            else
                $ok=0;
            echo "<val>{$phpinfo['PHP Core']['memory_limit']}</val><ok>$ok</ok>";
        }
        else
           echo "<val></val><ok>0</ok>";
    }
    else
        echo "<val></val><ok>0</ok>";
    echo "</phpmem>\n"; 

Solution

  • Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.

    <?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 >= 64 * 1024 * 1024); // at least 64M?
    
    echo '<phpmem>';
    echo '<val>' . $memory_limit . '</val>';
    echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
    echo '</phpmem>';
    

    Please note that the above code is just an idea. Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.