Output of "watch" -> PHP

Status
Not open for further replies.
16 comments
Ok, now I have this:

Code:
<?php
$cmd = "ps aux | grep apache | wc -l";
$output = system($cmd);
printf("Apache: $output\n");
echo "<br \>";

function get_memory() {
  foreach(file('/proc/meminfo') as $ri)
    $m[strtok($ri, ':')] = strtok('');
  return 100 - round(($m['MemFree'] + $m['Buffers'] + $m['Cached']) / $m['MemTotal'] * 100);
}
echo get_memory();
?>

Which results in:

Code:
90 Apache: 90 
67

How can I:
* remove the first '90'?
* make the 2nd '90' green untill '95' and red at or above '110'?
(Switch colors @ certain #)

Thanks for the help, I'm just a learner ;)
 
PHP:
<?php
$cmd = "ps aux | grep apache | wc -l";
$output = exec($cmd);

//Parse output
if ($output > 10)
{
$output = "Green time!";
}
printf("Apache: $output\n");
echo "<br \>";

function get_memory() {
  foreach(file('/proc/meminfo') as $ri)
    $m[strtok($ri, ':')] = strtok('');
  return 100 - round(($m['MemFree'] + $m['Buffers'] + $m['Cached']) / $m['MemTotal'] * 100);
}

?>

Edit: Checked your code, made some modifications for you. You STILL need to edit part of it, esp. the part on the output to make it green, right now as long as it is bigger than 10, it will make it 'green' to make it green you need to output something like
PHP:
$output = "<font color=green>" . $output . "</font>";

Something along those lines. I'm tired. If you still have any problem's ill guide you along tmr XD
 
Last edited:
Awesome!

Made some modifications.
This script now turns the text red if there are more than 80 apache users or green if there are less.

Stay tuned for more :)

PHP:
<?php
$cmd = "ps aux | grep apache | wc -l";
$output = exec($cmd);

//Parse output
if ($output > 80)
{
$output = "<font color=red>".  $output . "</font> apache users";

printf("Apache: $output\n");
echo "<br \>";
}
elseif ($output < 79)
{
$output = "<font color=green>".  $output . "</font> apache users";
printf("Apache: $output\n");
echo "<br \>";
}

function get_memory() {
  foreach(file('/proc/meminfo') as $ri)
    $m[strtok($ri, ':')] = strtok('');
  return 100 - round(($m['MemFree'] + $m['Buffers'] + $m['Cached']) / $m['MemTotal'] * 100);
}

?>
 
Fyi, system was outputting an extra 90 before Apache: 90, thats why i changed it to exec instead.

If you're interested, learn to use shorthand if's, makes your code look neater and shorter, although it is harder to read :)
 
Basically, Apache has a nice page where you can view the statistics, number of processes, processed requests, etc etc. Lots of information.

How to enable it?
Check the 'server-status' lines in httpd.conf (default location in RHEL installation is /etc/httpd/conf/httpd.conf).

You also need to enable 'extendedstatus'. Search for both those values in httpd.conf and you'll find them.

P.S: The number of apache processes returned by 'ps aux' is not always the number of connected users. Depending on your configuration, it could be idle children waiting to process a request. So your technique is kind of flawed :)
 
Ah, apache status page! :) Now I know what he ment B-)
Apache status page is not good enough, I'd like to have a small monitoring page where I can see a status overview of "all" my servers (and Nagios is to much).

Would you have any idea to a better way to determine the actual number of connected users?

Basically, Apache has a nice page whe
re you can view the statistics, number of processes, processed requests, etc etc. Lots of information.

How to enable it?
Check the 'server-status' lines in httpd.conf (default location in RHEL installation is /etc/httpd/conf/httpd.conf).

You also need to enable 'extendedstatus'. Search for both those values in httpd.conf and you'll find them.

P.S: The number of apache processes returned by 'ps aux' is not always the number of connected users. Depending on your configuration, it could be idle children waiting to process a request. So your technique is kind of flawed :)
 
Work in progress...

110638.jpg


It's quite instable.
Often the CSS doesn't load or the page just blanks :)

PHP:
<head>
<style type="text/css">
.green-square {
        background-color: #0f0;
        display: block;
        height: 70px;
        width: 70px;
        -moz-border-radius: 35px;
        border-radius: 35px;
.red-square {
        background-color: #DF0101;
        display: block;
        height: 150px;
        width: 150px;
}
</style>
<meta http-equiv="refresh" content="1" />
</head>
<?php

// Get number of connected users
$cmd = "ps aux | grep apache | wc -l";
$output = exec($cmd);

// Get free memory
function get_memory() {
  foreach(file('/proc/meminfo') as $ri)
    $m[strtok($ri, ':')] = strtok('');
  return round($m['MemFree'] / 1024);
}

//Parse output
if ($output > 100)
{
echo "<span class='red-square'><center>";
printf( $output);
echo "<br \>" . get_memory();
echo "</span><br \><br \>Server 1";
}
elseif ($output < 99)
{
echo "<span class='green-square'><br \><center>";
printf( $output);
echo "<br \>" . get_memory();
echo "</span><br \><br \>Server 1";
}


?>
 
Ah, apache status page! :) Now I know what he ment B-)
Apache status page is not good enough, I'd like to have a small monitoring page where I can see a status overview of "all" my servers (and Nagios is to much).

Would you have any idea to a better way to determine the actual number of connected users?

Use the Apache status page and do a preg_match on 'x requests currently being processed'. That's the true number of connections Apache is currently processing.
 
PHP:
//Assuming http://127.0.0.1/server-status is the apache page
$data = file_get_contents("http://127.0.0.1/server-status");
preg_match('#<dt>(.*) requests currently being processed#', $data, $match);
print_r($match);
//use the appropriate array to output result

^ Not tested. You could also use curl to possibly avoid reading the whole page into a single variable.

EDIT: Tested code below

PHP:
<?php

$data = file_get_contents("http://localhost/server-status");
preg_match('#<dt>(.*) requests currently being processed#', $data, $match);
$connections = trim($match[1]);
echo $connections;

?>

In a function:
PHP:
function get_connections($url) {
 $data = file_get_contents($url);
 preg_match('#<dt>(.*) requests currently being processed#', $data, $match);
 $connections = trim($match[1]);
 return($connections)
}
 
Last edited:
Cheers for that lifehacker.

If updated the script now to update using ajax.
It's becoming a uber cool server monitoring app :)

index.php
PHP:
<html>
<head>
<style type="text/css">
.green-circle {
        background-color: #0f0;
        display: block;
    height: 90px;
    width: 90px;
    -moz-border-radius: 45px;
    border-radius: 45px;}
.red-circle {
        background-color: #DF0101;
        display: block;
        height: 90px;
        width: 90px;
        -moz-border-radius: 45px;
        border-radius: 45px;
}
</style>
<script language="javascript" type="text/javascript" src="jx.js"></script>
<script type='text/javascript'>
function LoadAll() {
        jx.load("getdata.php",function(data) {
                document.getElementById('container').innerHTML = data;
        },'text');
        setTimeout("LoadAll()",1000);
}
</script>
</head>
<body onload='LoadAll()'>
<div id='container'>

</div>
</body>
</html>
getdata.php
PHP:
<?php

// Get number of connected users
$cmd = "ps aux | grep apache | wc -l";
$output = exec($cmd);

// Get CPU load
$uptime = exec("uptime");
$parts = split("load average:", $uptime);
$load = split(", ", $parts[1]);

// Get free memory
function get_memory() {
  foreach(file('/proc/meminfo') as $ri)
    $m[strtok($ri, ':')] = strtok('');
  return round($m['MemFree'] / 1024);
}


//Parse output
if ($output > 140)
{
echo "<span class='red-circle'><br /><center>";
printf( $output);
echo "<br />" . get_memory() . "/1024";
echo $load[0];
echo "</span><br /><br />Server 1";
}
elseif ($output < 140)
{
echo "<span class='green-circle'><br /><center>";
printf( $output);
echo "<br />" . get_memory() . "/1024";
echo $load[0];
echo "</span><br /><br />Server 1<br /><br />";
}


?>
jx.js
PHP:
//V3.01.A - http://www.openjs.com/scripts/jx/
jx = {
        //Create a xmlHttpRequest object - this is the constructor.
        getHTTPObject : function() {
                var http = false;
                //Use IE's ActiveX items to load the file.
                if(typeof ActiveXObject != 'undefined') {
                        try {http = new ActiveXObject("Msxml2.XMLHTTP");}
                        catch (e) {
                                try {http = new ActiveXObject("Microsoft.XMLHTTP");}
                                catch (E) {http = false;}
                        }
                //If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
                } else if (window.XMLHttpRequest) {
                        try {http = new XMLHttpRequest();}
                        catch (e) {http = false;}
                }
                return http;
        },
        // This function is called from the user's script.
        //Arguments -
        //      url     - The url of the serverside script that is to be called. Append all the arguments to
        //                      this url - eg. 'get_data.php?id=5&car=benz'
        //      callback - Function that must be called once the data is ready.
        //      format - The return type for this function. Could be 'xml','json' or 'text'. If it is json,
        //                      the string will be 'eval'ed before returning it. Default:'text'
        load : function (url,callback,format) {
                var http = this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
                if(!http||!url) return;
                if (http.overrideMimeType) http.overrideMimeType('text/xml');

                if(!format) var format = "text";//Default return type is 'text'
                format = format.toLowerCase();

                //Kill the Cache problem in IE.
                var now = "uid=" + new Date().getTime();
                url += (url.indexOf("?")+1) ? "&" : "?";
                url += now;

                http.open("GET", url, true);

                http.onreadystatechange = function () {//Call a function when the state changes.
                        if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
                                if(http.status == 200) {
                                        var result = "";
                                        if(http.responseText) result = http.responseText;

                                        //If the return is in JSON format, eval the result before returning it.
                                        if(format.charAt(0) == "j") {
                                                //\n's in JSON string, when evaluated will create errors in IE
                                                result = result.replace(/[\n\r]/g,"");
                                                result = eval('('+result+')');
                                        }

                                        //Give the data to the callback function.
                                        if(callback) callback(result);
                                } else { //An error occured
                                        if(error) error(http.status);
                                }
                        }
                }
                http.send(null);
        },
        init : function() {return this.getHTTPObject();}
}
 
Last edited:
Status
Not open for further replies.
Back
Top