Gauging cPanel bandwidth usage w/ Google Charts API

Following on from yesterdays blog post regarding gauging cPanel disk space with Google Charts API, we will now replicate this to create the bandwidth meter.

To get the disk space usage, we run the accountsummary function and return all the data, this data includes near enough every specific peace of information you would need regarding an account – except for total/average uses… No idea why. I sort of see the point (multiple domains on 1 account) but we should atleast get an overall or an average reading inaccountsummary.

Anyway, to get bandwidth readings, we do a similar query, this time using the showbw function.

[php]
$query = “https://127.0.0.1:2087/json-api/showbw?search=paulor&searchtype=user”;
[/php]

This will return a JSON feed containing all my main domain, subdomains, addon domains & parked domains, each with individual bandwidth usage, there is also a TOTAL bandwidth usage and a limit value. Its all pretty self explanitory, so ill just give you the code.

[php]
## WHM ROOT USER & HASH
$whmusername = “root”;
$whmhash = “098A7SDF89AS07DF897ASDF987SD987VXZC897BV98Z7XCV8755
06ZXC7V908Z7XC9V870X97ZC98V790Z7V9087CV907ZXC7V9ZCV9087ZX987V98
077ZXCV7ZX8C7V897ZXC8V78ZX7VC87XZC87V89XZ7CV878X9ZC7V8XZ7CV897Z
08X89CV789XZ7CV897ZXC8V789XCZ7V87ZXC8V798XZ7CV897XZC89V7ZX89C7V
0989XZ7CV897XZC8V789ZX7VC89Z7XCV87Z89XC7V89Z7XCV8ZX7V987XZVCGFD”;

## THE QUERY TO THE API
$query = “https://127.0.0.1:2087/json-api/showbw?search=paulor&searchtype=user”;

## CRAZY CURL STUFF TO AUTH AND RETURN DATA
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
$header[0] = “Authorization: WHM $whmusername:” . preg_replace(“‘(\r|\n)'”,””,$whmhash);
curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_URL, $query);
$result = curl_exec($curl);
if ($result == false) {
error_log(“curl_exec threw error \”” . curl_error($curl) . “\” for $query”);
}
curl_close($curl);

## COVERT BYTES TO MEGABYTES
function MBFormat($bytes,$decimals=1) {
return round($bytes/(1024*1024));
}

## DECODE JSON
$obj = json_decode($result);

## ROUND THE DIGITS
$bw_limit = round(MBFormat($obj->bandwidth[0]->acct[0]->limit)); // LIMIT
$bw_used = round(MBFormat($obj->bandwidth[0]->totalused)); // USED

echo ‘Bandwidth Used: ‘.$bw_used.’MB
‘;
echo ‘Bandwidth Limit: ‘.$bw_limit.’MB’;

## NOW JAVASCRIPT FROM GOOGLE CHARTS :]
?>



[/php]