get system total memory in php

To get the total memory of the server in PHP, we can use the memory_get_peak_usage() function. It returns the peak memory usage in bytes, from the start of the script execution.

To convert it to a more readable format, we can use the memory_format() function which takes in the byte count and returns it in MB, GB or TB format, depending on the size.

main.php
// function to format memory size
function memory_format($bytes) {
    $sizes = array('B', 'KB', 'MB', 'GB', 'TB');
    $i = floor(log($bytes, 1024));
    return round($bytes / pow(1024, $i), 2) . ' ' . $sizes[$i];
}

// get total memory
$total_memory = memory_format(@ini_get('memory_limit'));
echo "Total Memory: " . $total_memory;
334 chars
11 lines

Note: memory_get_peak_usage() may not work in all environments, or may return inaccurate results due to various factors such as caching, or other processes running on the server.

related categories

gistlibby LogSnag