logo

PHP Disk Space Explorer Class

Add comment

In this tutorial I’ll show you how to create a script that will create graphs. Those graphs will contain information about your files, their extensions and their size. We will use Google and their API for creating graphs. So lets start.

First, we will create a class named folderStructure.

class folderStructure
{
//Here will go our functions.
}

After that we will create some variables. They will help us to create some basic config.

protected $_types                    = array(
  0 => 'Images',
  1 => 'Music',
  2 => 'Videos',
  3 => 'Documents',
  4 => 'Compressed',
  5 => 'Execatubles',
  6 => 'Other'
);

protected $_size                     = 0;

protected $_filesCount               = 0;

protected $_typesCount               = array(
   0 => 0,
   1 => 0,
   2 => 0,
   3 => 0,
   4 => 0,
   5 => 0,
   6 => 0
);

protected $_sizes                    = array(
   '>1GB'         => array(
      'from' => 1073741824
   ),
   '500MB-1GB'    => array(
      'from' => 524288000,
      'to'   => 1073741824
   ),
   '100MB-500MB'  => array(
      'from' => 104857600,
      'to'   => 524288000
   ),
   '50MB-100MB'   => array(
      'from' => 52428800,
      'to'   => 104857600
   ),
   '10MB-50MB'    => array(
      'from' => 10485760,
      'to'   => 52428800
   ),
   '1MB-10MB'     => array(
      'from' => 1048576,
      'to'   => 10485760
   ),
   '<1MB'         => array(
      'to'   => 1048576
   )
);

protected $_sizesCount               = array(
  '>1GB'         => 0,
  '500MB-1GB'    => 0,
  '100MB-500MB'  => 0,
  '50MB-100MB'   => 0,
  '10MB-50MB'    => 0,
  '1MB-10MB'     => 0,
  '<1MB'         => 0
);

protected $_extensions               = array(
   'gif'       => 0,
   'png'       => 0,
   'jpeg'      => 0,
   'jpg'       => 0,
   'bmp'       => 0,
   'mp3'       => 1,
   'wma'       => 1,
   'wav'       => 1,
   'mp4'       => 2,
   'avi'       => 2,
   'mpeg'      => 2,
  'mov'       => 2,
  'flv'       => 2,
  'mkv'       => 2,
   'wmv'       => 2,
  'doc'       => 3,
  'pdf'       => 3,
  'css'       => 3,
  'html'      => 3,
  'html'      => 3,
  'php'       => 3,
  'xml'       => 3,
  'js'        => 3,
  'docx'      => 3,
  'ppt'       => 3,
  'pptx'      => 3,
  'txt'       => 3,
   'zip'       => 4,
   'rar'       => 4,
   '7z'        => 4,
   'msi'       => 5,
   'exe'       => 5,
  'jar'       => 5
);

protected $_eachExtension              = array();

So let me explain wat each of them does. First we have $_types. That is an array and it is for reference to $_extensions variable. One of keys in $_types is a value for one of the keys in $_extensions. We use it like that, so we know which extension is for which type. After that comes $_size. This will be size of the whole folder (including sub-folders). $_files count will have count of all files in that folder and all sub-folders. $_typesCount will have count for each type that we have in $_types. $_sizes is an array that is used when looking at which group of sizes should our file go. $_sizes and $_sizesCount have same keys so we can connect them. Each key in $_sizes has a value of an array that has 1 or 2 keys. They are used for comparison as you will see later. $_sizesCount is used to save counts of files that are within that group. $_extensions has for keys extension name. Values are keys from $_types variable in which group it is (did not explain it to good but here is an example). So our key is gif and since it's an image, it goes to Images category. If you look at our $_types, you'll se that Images has key 0. I made it like that so you can easily add more extensions. And last we have $_eachExtension. It's an empty array that will have all extensions and it's count.

So, now that we have our variables in place, we can start creating our function. First we'll have a countructor that will take as an argument folder path. If that folder does not exists, it will throw an Exception. If folder exists it will start collecting information about it. Function _getFolderStats will be our main function, and will create it next.

public function __construct($folderPath)
{
  if(!is_dir($folderPath))
     throw new Exception('Folder "' . $folderPath . '" does not exist.');

  $this->_getFolderStats($folderPath);
}

Next we'll have a function _getFolderStats. Since it's a bit larger function, we'll buld it part by part.

protected function _getFolderStats($folderPath)
{
   $folder = new DirectoryIterator($folderPath);

   while ($folder->valid()) {

      if ($folder->isDot()) {
         $folder->next();
         continue;
      }

      if ($folder->isDir()) {
         $this->_getFolderStats($folder->getPathname());
         $folder->next();
         continue;
      }

      //Next part goes instead of this comment.

      $folder->next();
   }
}

Our function accepts 1 argument, and that is our path to folder. We use PHP-s class DirectoryIterator (SPL clsss). Then we have a simpel while loop. We check if current entry is valid. If it is, then we loop again, otherwise we exit our loop. At the end of our loop we advance our pointer to next entry. Then we check if our current entry is a dot (current folder '.' or parent folder '..'). It that's true, then we just skip it and go to the next entry. Then we check if our entry is a folder. If that's true, then we run this function again (this function is recursive) and go to the next entry. Now comes the other part of this function.

$extension = strtolower(substr($folder->getFilename(), strrpos($folder->getFilename(), '.') + 1));

if (isset($this->_extensions[$extension]))
   $this->_typesCount[$this->_extensions[$extension]]++;
else
   $this->_typesCount[6]++;

if (isset($this->_eachExtension[$extension]))
   $this->_eachExtension[$extension]++;
else
   $this->_eachExtension[$extension] = 1;

$size = $folder->getSize();

$this->_size += $size;
$this->_filesCount += 1;

foreach ($this->_sizes as $sizeName => $values) {
   if (isset($values['from']) && isset($values['to'])) {
      if ($size > $values['from'] && $size < $values['to']) {
         $this->_sizesCount[$sizeName]++;
          break;
      }
   }
   elseif (isset($values['from'])) {
      if ($size > $values['from']) {
         $this->_sizesCount[$sizeName]++;
         break;
      }
   }
   else {
      if ($size < $values['to']) {
         $this->_sizesCount[$sizeName]++;
         break;
      }
   }
}

Now we use our variables that we defined at the beginning. First we get current extension (this is not the best way to do it, but you'll get the point). We just substract our file name from index that has last dot to the end of that string. Now we check if we have that extension in our $_extensions. (remember that each extension has it's category). If we have it, then increment that category in $_typesCount. If we do not have, then increment unkown category. Then we do almost the same thing with our $_eachExtension. If we have current extension in our array, then increment it. If we do not, create a key for it and assing 1 to it. Then we get size of our file. We add it to whole directory size ($_size). We also increment by 1 variable $_filesCount. Last thing we need to do, is to determine in which length group our file goes. To do that we loop each row.

Now that we have our function that collects data, we need some functions to echo those data back to us so we can see them. For that pourpose we will use google chart. We will have 5 functions. First 3 will generate graphs, ans other 2 will just return values. So lets start.

public function getSizeChart()
{
   $keys = $values = '';
   foreach ($this->_sizesCount as $sizeKey => $value) {
      $keys .= $sizeKey . '|';
      $values .= ((int) (($value / $this->_filesCount) * 100)) . ',';
   }
?>
<img src="http://chart.apis.google.com/chart?chs=500x300&chd=t:<?php echo substr($values, 0, -1); ?/>&cht=p&chl=< ?php echo substr($keys, 0, -1); ?>" />
< ?php
   return $this;
}

public function getTypesChart()
{
   $keys = $values = '';
   foreach ($this->_typesCount as $typeKey => $value) {
      $keys .= $this->_types[$typeKey] . '|';
      $values .= ((int) (($value / $this->_filesCount) * 100)) . ',';
}
?>
<img src="http://chart.apis.google.com/chart?chs=500x300&chd=t:<?php echo substr($values, 0, -1); ?/>&cht=p&chl=< ?php echo substr($keys, 0, -1); ?>" />
< ?php
   return $this;
}	

public function getExtensionsChart()
{
   $keys = $values = '';
   foreach ($this->_eachExtension as $extensionKey => $value) {
      $keys .= $extensionKey . '|';
      $values .= ((int) (($value / $this->_filesCount) * 100)) . ',';
   }
?>
<img src="http://chart.apis.google.com/chart?chs=500x300&chd=t:<?php echo substr($values, 0, -1); ?/>&cht=p&chl=< ?php echo substr($keys, 0, -1); ?>" />
< ?php
   return $this;
}

public function getNumberOfFiles()
{
   return $this->_filesCount;
}

public function getFolderSize()
{
   return $this->_size;
}

I think this does not need to be explained to much. In first 3 functions we just loop our data and create string to query google. For more information check on google how to use their graph.

To use it, we just create instance of our class and pass our folder path. Then we echo graphs. Methods can be chained as you can see bellow.

$graph = new folderStructure('/Users/marijan/Filmovi');
$graph->getExtensionsChart()->getSizeChart()->getTypesChart();
echo '<br />';
echo 'Folder size: ', $graph->getFolderSize();
echo '<br />';
echo 'Number of files: ', $graph->getNumberOfFiles();

That code will produce something simillar to this picture.

Rezult

Rezult

I hope you liked my tutorial and you will come back. You  can download the whole script here. Thanks for reading.


logo

Leave a Reply


 *


 *


logo
logo
Powered by Wordpress | Designed by Elegant Themes | CopyRight ©2014 php4every1.com