02
Jun '14

Getting Server Information in PHP

I’ve been having a go at pulling server information and stats out of PHP as a ‘nice to have’ for an application I’m building. It turns out that you can retrieve a fair bit of information from a Linux system if you’re not afraid of wrapping a few system calls. Here’s my finished script, please feel free to use at will!

$stats = array(
    'Host Name' => exec('hostname'),
    'System Date/Time' => date('Y-m-d H:i:s')
);

$uptime_parts = explode(' ', file_get_contents('/proc/uptime'));
$uptime_raw = $uptime_parts[0];
$days = floor($uptime_raw / 86400);
$hours = ($uptime_raw / 3600) % 24;
$minutes = ($uptime_raw / 60) % 60;
$seconds = $uptime_raw % 60;

$stats['Uptime'] = $days . ' day(s), ' . $hours . ' hour(s), ' . $minutes . ' minute(s) and ' . $seconds . ' second(s)';

$load_parts = sys_getloadavg();
$load_average = $load_parts[0];

$stats['Load Average'] = $load_average;

$memory_data = preg_split('/[\r\n]/', file_get_contents('/proc/meminfo'));

if($memory_data && count($memory_data) >= 2) {
    $memory_total_parts = array_values(array_filter(explode(' ', $memory_data[0])));
    $memory_total = number_format(($memory_total_parts[1] / 1000000), 2);
    $memory_free_parts = array_values(array_filter(explode(' ', $memory_data[1])));
    $memory_free = number_format(($memory_free_parts[1] / 1000000), 2);

    $stats['Total Memory'] = $memory_total . ' GB';
    $stats['Available Memory'] = $memory_free . ' GB';
}

$stats['Total Disk Space'] = number_format((disk_total_space('/') / 1000000000), 2) . ' GB';
$stats['Available Disk Space'] = number_format((disk_free_space('/') / 1000000000), 2) . ' GB';

Leave a Reply