Sunday, December 8, 2013

PHP script for showing computer info

For those wanting to print out information about their server to a web page: I designed the following php script to do that on a Linux server.

 <?php  
      //Removes everything before the first ':' character, meant to get information from /proc/cpuinfo  
      function extractCPUInfoLine($inputString)  
      {  
           return trim(substr($inputString, strpos($inputString, ':') + 1));   
      }  
      //Returns an array of info for the processor  
      function getCPUInfo()  
      {  
           $cpufile = file("/proc/cpuinfo");  
           $memFile = file("/proc/meminfo");  
           $cpuinfoArray = array();  
           $cpuinfoArray["cpu"] = extractCPUInfoLine($cpufile[4]);  
           $cpuinfoArray["speed"] = extractCPUInfoLine($cpufile[7]) . " Mhz";  
           $cpuinfoArray["cache"] = extractCPUInfoLine($cpufile[8]);  
           $cpuinfoArray["memory"] = extractCPUInfoLine($memFile[0]);  
           return $cpuinfoArray;   
      }  
 ?>  

 <html>  
      <head>  
           <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">  
           <title>Server Info</title>  
           <link rel="stylesheet" type="text/css" href="style.css">  
      </head>  
      <body>  
           <h2>About This Server</h2>  
           <?php  
                $cpuInfoArray = getCPUInfo();  
                print "          <table>  
                <tr>  
                     <td>CPU</td>  
                     <td>" . $cpuInfoArray["cpu"] . "</td>  
                </tr>  
                <tr>  
                     <td>CPU Speed</td>  
                     <td>" . $cpuInfoArray["speed"] . "</td>  
                </tr>  
                <tr>  
                     <td>Memory</td>  
                     <td>" . $cpuInfoArray["memory"] . "</td>  
                </tr>  
                <tr>  
                     <td>Cache</td>  
                     <td>" . $cpuInfoArray["cache"] . "</td>  
                </tr>  
                <tr>  
                     <td>Total disk space</td>  
                     <td>" . number_format(disk_total_space("/home") / (1024 * 1024 * 1024), 3) . " Gb</td>  
                </tr>  
                <tr>  
                     <td>Free disk space</td>  
                     <td>" . number_format(disk_free_space("/home") / (1024 * 1024 * 1024), 3) . " Gb</td>  
                </tr>  
           </table>";  
           ?> 
      </head>  
 </html>  



This script will print out the CPU type, speed, memory size, cache size and total and available disk space.

The trick is that within most Linux systems there are files under the /proc directory, such as procinfo and meminfo, which tells you information about your computer's cpu and memory. Getting basic computer info is a matter of reading those files.

No comments: