How to get Memory and CPU usage in PHP

Created September 27, 2012

So, a couple weeks ago I experienced heavy server overloads on an app due to so many concurrent users. There may have also been some code clean up that was necessary. Either way it was kind of a headache, but also a learning experience. So upon searching the interent I could not find an easy way to print out the Server Memory Usage or CPU Usage as a percentage. So, with the help of some string manipulation and a fellow co-worker we created these 2 php functions. These configurations worked on a MediaTemple (ve) server with Ubuntu 11.04. The first function will return the Server Memory Usage:

function get_server_memory_usage(){
	$free = shell_exec('free');
	$free = (string)trim($free);
	$free_arr = explode("\n", $free);
	$mem = explode(" ", $free_arr[1]);
	$mem = array_filter($mem);
	$mem = array_merge($mem);
	$memory_usage = $mem[2]/$mem[1]*100;

	return $memory_usage;

This function will return the Server CPU Usage:

function get_server_cpu_usage(){

	$load = sys_getloadavg();
	return $load[0];


So, if you were to call the two functions in a php file like this:

<p><span class="description">Server Memory Usage:</span> <span class="result">= get_server_memory_usage() ?&gt;%</span></p>
<p><span class="description">Server CPU Usage: </span> <span class="result">= get_server_cpu_usage() ?&gt;%</span></p>

You'll probably end up with a page that looks similar:

And that's how you can get the server memory and cpu usage from PHP. I hope that these function can help someone else along the way.