Thursday, 13 October 2011

PHP: Getting disk usage (class)

I thought I might as well post this class I wrote a while ago. It basically gathers the following for the specific drive you've selected;
  • Raw Total Size
  • Raw Free Size
  • Readable Total Size
  • Readable Free Size
  • Percentage Free
  • Percentage Used
The Class
<?php
class diskSpace
{
 function __construct( $disk = '.' )
 {
  $this->the_drive = $disk;
  $this->raw_diskspace = $this->disk_spaces( "total" );
  $this->raw_freespace = $this->disk_spaces( "free" );
  $this->readable_diskspace = $this->readableSizes( $this->raw_diskspace );
  $this->readable_freespace = $this->readableSizes( $this->raw_freespace );
  $this->percentage_free = $this->percentages( "free" );
  $this->percentage_used = $this->percentages( "used" );
 }
 
 public function disk_spaces( $type )
 {
  switch($type)
  {
   case "total":
    return disk_total_space( $this->the_drive );
   break;
   case "free":
    return disk_free_space( $this->the_drive );
   break;
  }
 }
 
 public function readableSizes( $size )
 {
  $types = array( ' B', ' KB', ' MB', ' GB', ' TB', ' TB', ' EB', ' ZB', ' YB' );
  $i=0;
  while($size>=1024)
  {
   $size/=1024;
   $i++;
  }
  return("".round($size,2).$types[$i]);
 }
 
 public function percentages( $type )
 {
  switch($type)
  {
   case "free":
    return (round($this->raw_freespace / $this->raw_diskspace, 2) * 100) . "%";
   break;
   case "used":
    return round(100 - $this->percentage_free) . "%";
   break;
  }
 }
}
?>
The Usage
<?php
// load class with default drive
$dUsage = new diskSpace;

// or load class with specific drive
$dUsage = new diskSpace( "." );
// how to call each option
print("The Disk: " . $dUsage->the_drive);
// will output: .

print("Raw Size: " . $dUsage->raw_diskspace);
// will output: Raw Size: 489616760832

print("Raw Free: " . $dUsage->raw_freespace);
// will output: Raw Free: 454473097216

print("Readable Size: " . $dUsage->readable_diskspace);
// will output: Readable Size: 455.99 GB

print("Readable Free: " . $dUsage->readable_freespace);
// will output: Readable Free: 423.26 GB

print("Percentage Free: " . $dUsage->percentage_free);
// will output: Percentage Free: 93%

print("Percentage Used: " . $dUsage->percentage_used);
// will output: Percentage Used: 7%
?>

1 comment:

  1. I have no words for this great post such a awe-some information i got gathered. Thanks to Author.

    ReplyDelete