• Getting the size of a directory

    It’s sometimes helpful to be able to get the amount of space being used in a directory, especially if you’re running a website on a limited bit of space.

    The following PHP function will work out the amount of space used, the amount of files in the directory, and the number of sub-directories. Simply call it with your desired path, eg /home/username/public_html/graphics

    function getDirectorySize($path) {
    $totalsize = 0;
    $totalcount = 0;
    $dircount = 0;
    if ($handle = opendir ($path)) {
    	while (false !== ($file = readdir($handle))) {
    	$nextpath = $path . '/' . $file;
    	if ($file != '.' && $file != '..' && !is_link ($nextpath)) {
    		if (is_dir ($nextpath))
    		{
    		  $dircount++;
    		  $result = getDirectorySize($nextpath);
    		  $totalsize += $result['size'];
    		  $totalcount += $result['count'];
    		  $dircount += $result['dircount'];
    		} elseif (is_file ($nextpath)) {
    		  $totalsize += filesize ($nextpath);
    		  $totalcount++;
    		}
    	  }
    	}
    }
    closedir ($handle);
    $total['size'] = $totalsize;
    $total['count'] = $totalcount;
    $total['dircount'] = $dircount;
    return $total;
    }

    This will return an array for you, so if you’ve called the function with $total=getDirectorySize(‘your_path’), you can now find the individual pieces of information using $total[0] for size, $total[1] for file count and $total[2] for directory count.

    You’ll find that the size of the directory is a bit unweildy, so the following function will convert it into a nice, easily-understood number for you!

    function sizeFormat($size) {
    	if($size<1024) {
    	     return $size." bytes";
    	} else if($size<(1024*1024)) {
    	     $size=round($size/1024,1);
    	     return $size."kb";
    	} else if($size<(1024*1024*1024)) {
    	     $size=round($size/(1024*1024),1);
    	     if ($size < 10) {
                      // HERE WE HAVE HIGHLIGHTED THAT
                      // THE SPACE LEFT IS LESS THAN 10 MB
                      return "<span style="color: #ff0000;">".$size."mb</span>";
    	     } else {
    		  return $size."mb";
    	     }
    	} else {
    	     $size=round($size/(1024*1024*1024),1);
    	     return $size."gb";
    	}
    }

    To convert the size, simply call the function thus, $size=sizeFormat($total[0]); and then echo out your converted size.

    Share and Enjoy:
    • Digg
    • Sphinn
    • del.icio.us
    • Facebook
    • Mixx
    • Google Bookmarks

     Leave a reply