Linux uptime

If you want to show the uptime of your linux server on your website, you can do so very easily.

function linuxUptime() {
  $ut = strtok( exec( "cat /proc/uptime" ), "." );
  $days = sprintf( "%2d", ($ut/(3600*24)) );
  $hours = sprintf( "%2d", ( ($ut % (3600*24)) / 3600) );
  $min = sprintf( "%2d", ($ut % (3600*24) % 3600)/60  );
  $sec = sprintf( "%2d", ($ut % (3600*24) % 3600)%60  );
  return array( $days, $hours, $min, $sec );

$ut = linuxUptime();
// If you would like to show the seconds as well just add [ , $ut[3] seconds ] after minutes.
echo "Time since last reboot: $ut[0] days, $ut[1] hours, $ut[2] minutes";

Just call the $ut = linuxUptime() function and then you can use the variables to show the time.

**NOTE: Your server must allow you to run the exec() PHP command. Some hosts disable the execution of this and several other PHP functions.

Now if you were wanting to gather the uptime of multiple servers all at the same time this can be accomplished with CURL. What we would end up doing is using the above code and place it in a PHP file on each of the target servers. In the example below you will see I am referencing a file called linuxUptime.php which holds the code listed above. We could then use a MySQL database or just an array full of domain names that we would loop through to gather the stats. Below I am posting a simple script which uses an array as an example. (This file does not currently exist on my site to show uptime of my site)

$sites = array(''); // Create a list of sites to check
foreach($sites as $site) { // Loop through each site and get uptime

$ch = curl_init(); // Initiate curl session
curl_setopt($ch, CURLOPT_URL, 'http://'.$site.'/linuxUptime.php'); // Set the URL of the uptime script
curl_setopt($ch, CURLOPT_HEADER, 0); // Disable header output
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // Return data as a string instead of output directly
$data=curl_exec($ch); // Execute curl commands
curl_close ($ch); // Close the curl session

echo $site.': '.$data.'<br />'; // Output value returned from the linuxUptime.php file
} // End server loop

When we gather stats like this we could easily store the uptime values in a database table so that we could track the history.


  • Facebook
  • Digg
  • Google Bookmarks
  • BlinkList
  • FriendFeed
  • LinkedIn
  • MySpace
  • Slashdot
  • StumbleUpon
  • Twitter
  • Yahoo! Bookmarks
  • Add to favorites
  • email

Comments are closed.

Switch to our mobile site