Hi Guys,
If you need to know the size of a directory, how many subdirectories or files have this utility class might come very handy.
This class can traverse the directory that you indicate response and bring the same size in Megabytes, Gigabytes or Kilobytes as well as the number of files and directories it contains.
Let’s code. 🙂
<?php /** * Display the disk usage for a particular user/folder. * * @package Disk Usage * @author Nitesh Apte * @copyright 2010 * @version 1.0 * @access public * @License GPL */ final class DiskUsage { var $_totalSize = 0; var $_totalCount = 0; var $_directoryCount = 0; var $_handleDir; var $_filePath; var $_nextPath; var $_resultValue; var $_totalValue = array(); public function _directorySize($_path) { if($_handleDir = opendir($_path)) { while(FALSE !== ($_filePath = readdir($_handleDir))) { $_nextPath = $_path . "/" . $_filePath; if($_filePath != '.' && $_filePath != '..' && !is_link($_nextPath)) { if(is_dir($_nextPath)) { $_directoryCount++; $_resultValue = self::_directorySize($_nextPath); $_totalSize += $_resultValue['size']; $_totalCount += $_resultValue['count']; $_directoryCount += $_resultValue['dircount']; } elseif(is_file($_nextPath)) { $_totalSize += filesize($_nextPath); $_totalCount++; } } } } closedir($_handleDir); $_totalValue['size'] = $_totalSize; $_totalValue['count'] = $_totalCount; $_totalValue['dircount'] = $_directoryCount; return $_totalValue; } public function _sizeFormat($_dirSize) { if($_dirSize < 1024) { return $_dirSize." Bytes."; } else if($_dirSize < (1024*1024)) { $_dirSize = round($_dirSize/1024,1); return $_dirSize." KB."; } else if($_dirSize < (1024*1024*1024)) { $_dirSize = round($_dirSize/(1024*1024),1); return $_dirSize + 0.1." MB."; } else { $_dirSize = round($_dirSize/(1024*1024*1024),1); return $_dirSize." GB."; } } } ?>
How to use it:
<?php include 'class.DiskUsage.php'; $obj = new DiskUsage; $path= "/var/www/example/"; $size = $obj->_directorySize($path); echo "Details for the path :". $path; echo "Total size : ".$obj->_sizeFormat($size['size']); echo "No. of files : ".$size['count']; echo "No. of directories : ".$size['dircount']; ?>
If you do not know what the absolute path of a directory within our server, you can figure it out by running the following code:
echo $_SERVER['DOCUMENT_ROOT'];
That’s all folk.
Critics/suggestion are very much welcome.
Have a nice day ahead.
Leave a Reply