Kyle
Kyle

Reputation: 3042

How do you calculate server load in PHP?

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.

Upvotes: 4

Views: 21696

Answers (8)

SagarPPanchal
SagarPPanchal

Reputation: 10111

<?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.');
}
?>

Upvotes: 1

George Donev
George Donev

Reputation: 573

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;
}

Upvotes: 1

M_R_K
M_R_K

Reputation: 6350

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.

Upvotes: 0

Musznik
Musznik

Reputation: 94

function _loadavg()
{
    if(class_exists("COM")) 
    {
      $wmi = new COM("WinMgmts:\\\\.");
      $cpus = $wmi->InstancesOf("Win32_Processor");

      foreach ($cpus as $cpu) 
      {
       return $cpu->LoadPercentage;
      }
    } 
}

Upvotes: -1

jakubos
jakubos

Reputation: 105

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.

Upvotes: 9

E Ciotti
E Ciotti

Reputation: 4963

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];
}

Upvotes: 2

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

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;
}

Upvotes: 3

Khez
Khez

Reputation: 10350

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.

Upvotes: 14

Related Questions