A (very) simple disk usage report with quota + php gd

Ok, i need to show a report about disk usage for a linux account with php, this report would be a tiny little png file. i searh google and found some clues, but not really fix on me so i try to modify it a bit!

Since im not a php programmer or any other computer language programmer so my code not good, im sure if the code are in the right people (programmer of course!) then this code would be much better!

i need to inform you that my sistem is disk quota enabled, so if your sistem not use it, this code probably not work with you!

 

<?php
        function humanSizes($bytes) {
                $type = array("K", "M", "G", "T");
                $idx = 0;

                //quota give a value in bit, so we need to convert to byte!
        $bytes *= 1.024;

                while($bytes >= 1024)
                {
                        $bytes /= 1024;
                        $idx++;
                }

                return("".round($bytes, 2)."".$type[$idx]."b");
        }

        $myAccountSpace = exec("quota | grep -v -A 1 quota | gawk '{print $3}'");

        // if UNIX and variants!
        $used = exec("quota | grep -v -A 1 quota | gawk '{print $2}'");
        $usagePercentage = ($used * 100) / $myAccountSpace;

        //echo humanSizes($used)." of ".humanSizes($myAccountSpace)." used<br />";
        //echo "Usage percentage is: " . round($usagePercentage, 2) . "%<br />";
    $quota_report = humanSizes($used)." of ".humanSizes($myAccountSpace).", used ".round($usagePercentage, 2)."%";
   
$width = 180;
$height = 12;
$im0 = @imagecreate($width, $height)
      or die("Cannot Initialize new GD image stream");

//color
$background_im0 = imagecolorallocate($im0, 216, 230, 245);
$black = imagecolorallocate($im0, 0, 0, 0);
$green = imagecolorallocate($im0, 123, 215, 123);
$yellow = imagecolorallocate($im0, 250, 255, 38);
$red = imagecolorallocate($im0, 250, 31, 205);

//processing
$text_color = imagecolorallocate($im0, 0, 0, 0);
imagerectangle($im0, 0, 0, ($width – 1), ($height – 1), $black);

//if disk usage < 65% show green color bar, if between 65% and 85% show yellow
//if usage > 85% show red color bar!
if (round($usagePercentage, 2) < 65)
    $filled_color = $green;
elseif    (round($usagePercentage, 2) > 65 && round($usagePercentage, 2) < 85)
    $filled_color = $yellow;
else
    $filled_color = $red;

//create the bar!   
imagefilledrectangle($im0, 1, 1, (round($usagePercentage, 2)/100 * $width), 10, $filled_color);
imagestring($im0, 1, ($width / 11), 2, $quota_report, $text_color);
header ("Content-type: image/png");
imagepng($im0);
imagedestroy($im0);
?>

to insert the report on html page just give the file name as a src for img tag:

<img xsrc=quota_pbar.php>

 

This entry was posted in Information Technology, my life. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *