4

How do you calculate the server load of PHP/apache? I know in vBulletin forums there's the server load displayed like 0.03 0.01 0.04 but it's not really understandable to a average joe. So I thought about a 1-100 percentile scale. I wanted to display a server load visual that reads from a DIV:

$load = $serverLoad*100;
<div class=\"serverLoad\">
    <div style=\"width: $load%;\"></div>//show visual for server load on a 1-100 % scale
</div>
<p>Current server load is $load%</p>
</div>

However, I don't know how to detect server load. Is it possible to do turn this server load into a percentile scale? I don't know where to start. May someone please help me out?

Thanks.

Kyle
  • 3,004
  • 15
  • 52
  • 79

8 Answers8

14

I have a very old function that should still do the trick:

function getServerLoad($windows = false){
    $os=strtolower(PHP_OS);
    if(strpos($os, 'win') === false){
        if(file_exists('/proc/loadavg')){
            $load = file_get_contents('/proc/loadavg');
            $load = explode(' ', $load, 1);
            $load = $load[0];
        }elseif(function_exists('shell_exec')){
            $load = explode(' ', `uptime`);
            $load = $load[count($load)-1];
        }else{
            return false;
        }

        if(function_exists('shell_exec'))
            $cpu_count = shell_exec('cat /proc/cpuinfo | grep processor | wc -l');        

        return array('load'=>$load, 'procs'=>$cpu_count);
    }elseif($windows){
        if(class_exists('COM')){
            $wmi=new COM('WinMgmts:\\\\.');
            $cpus=$wmi->InstancesOf('Win32_Processor');
            $load=0;
            $cpu_count=0;
            if(version_compare('4.50.0', PHP_VERSION) == 1){
                while($cpu = $cpus->Next()){
                    $load += $cpu->LoadPercentage;
                    $cpu_count++;
                }
            }else{
                foreach($cpus as $cpu){
                    $load += $cpu->LoadPercentage;
                    $cpu_count++;
                }
            }
            return array('load'=>$load, 'procs'=>$cpu_count);
        }
        return false;
    }
    return false;
}

This returns processor load. You can also use memory_get_usage and memory_get_peak_usage for memory load.

If you can't handle finding percentages based on this... sigh, just post and we'll try together.

Khez
  • 10,172
  • 2
  • 31
  • 51
9

This function in PHP might do that trick: sys_getloadavg().

Returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively.

jakubos
  • 105
  • 1
  • 7
3
function get_server_load()
{

    $serverload = array();

    // DIRECTORY_SEPARATOR checks if running windows
    if(DIRECTORY_SEPARATOR != '\\')
    {
        if(function_exists("sys_getloadavg"))
        {
            // sys_getloadavg() will return an array with [0] being load within the last minute.
            $serverload = sys_getloadavg();
            $serverload[0] = round($serverload[0], 4);
        }
        else if(@file_exists("/proc/loadavg") && $load = @file_get_contents("/proc/loadavg"))
        {
            $serverload = explode(" ", $load);
            $serverload[0] = round($serverload[0], 4);
        }
        if(!is_numeric($serverload[0]))
        {
            if(@ini_get('safe_mode') == 'On')
            {
                return "Unknown";
            }

            // Suhosin likes to throw a warning if exec is disabled then die - weird
            if($func_blacklist = @ini_get('suhosin.executor.func.blacklist'))
            {
                if(strpos(",".$func_blacklist.",", 'exec') !== false)
                {
                    return "Unknown";
                }
            }
            // PHP disabled functions?
            if($func_blacklist = @ini_get('disable_functions'))
            {
                if(strpos(",".$func_blacklist.",", 'exec') !== false)
                {
                    return "Unknown";
                }
            }

            $load = @exec("uptime");
            $load = explode("load average: ", $load);
            $serverload = explode(",", $load[1]);
            if(!is_array($serverload))
            {
                return "Unknown";
            }
        }
    }
    else
    {
        return "Unknown";
    }

    $returnload = trim($serverload[0]);

    return $returnload;
}
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
2

If "exec" is activated

/**
 * Return the current server load
 * It needs "exec" activated
 *
 * e.g.
 * 15:06:37 up 10 days,  5:59, 12 users,  load average: 1.40, 1.45, 1.33
 * returns
 * float(1.40)
 */
public function getServerLoad()
{
    preg_match('#(\d\.\d+),[\d\s\.]+,[\d\s\.]+$#', exec("uptime"), $m);
    return (float)$m[1];
}
E Ciotti
  • 4,740
  • 1
  • 25
  • 17
1

Here is a windows/linux compatible php server load function:

function get_server_load() {
    $load = '';
    if (stristr(PHP_OS, 'win')) {
        $cmd = 'wmic cpu get loadpercentage /all';
        @exec($cmd, $output);
        if ($output) {
            foreach($output as $line) {
                if ($line && preg_match('/^[0-9]+$/', $line)) {
                    $load = $line;
                    break;
                }
            }
        }

    } else {
        $sys_load = sys_getloadavg();
        $load = $sys_load[0];
    }
    return $load;
}
George Donev
  • 563
  • 7
  • 13
1
<?php
$load = sys_getloadavg();
if ($load[0] > 0.80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?>
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. - [From review](https://stackoverflow.com/review/low-quality-posts/12011689) – Ferrybig Apr 14 '16 at 07:49
  • 1
    appreciative! thank you for your guide, will definitely keep in mind – SagarPPanchal Apr 14 '16 at 09:19
0

Its Pretty easy in LAMP environment if you have proper permissions,

print_r(sys_getloadavg());

OUTPUT : Array ( [0] => 0 [1] => 0.01 [2] => 0.05 )

Array values are average load in the past 1, 5 and 15 minutes respectively.

M_R_K
  • 5,929
  • 1
  • 39
  • 40
-1
function _loadavg()
{
    if(class_exists("COM")) 
    {
      $wmi = new COM("WinMgmts:\\\\.");
      $cpus = $wmi->InstancesOf("Win32_Processor");

      foreach ($cpus as $cpu) 
      {
       return $cpu->LoadPercentage;
      }
    } 
}
Musznik
  • 94
  • 2
  • 5