October 12, 2007

How to Display Server Load in PHP

Filed under: PHP — Matt @ 3:35 am

As the inaugural post on my new blog, I figured I’d start with something I put to good use today. When developing a PHP application or monitoring a web server, it’s important to know what your server load is to properly identify that there is a problem. This can be achieved through most control panel software (like WHM) or by typing in “uptime” in your SSH command prompt.

For those interested, there is a very easy way to output your load in PHP using the exec function. See the code below.

$load = exec(”uptime”);
$load = split(”load average:”, $load);
$load = split(”, “, $load[1]);
$load = $load[0];
echo “Current Load: $load”;

Place that snippet wherever you want in your PHP application to output the current server load. If you want to display something like “03:55:48 up 49 days, 13:36, 0 users, load average: 0.04, 0.12, 0.10″ instead of just “0.04″, you can delete lines 2-4 of the code.

Of course, since “uptime” is a Unix command this won’t work on Windows servers, and from what I understand, there’s no easy solution for those users.

« Previous Page