In PHP we have an inbuilt function called filesize() to get the size of any file, but what about a directory/ folder. A folder can content many files and sub folders in it. So lets write down a simple PHP function to calculate the folder size.

PHP Function

function folderSize($dir){
$count_size = 0;
$count = 0;
$dir_array = scandir($dir);
  foreach($dir_array as $key=>$filename){
    if($filename!=".." && $filename!="."){
       if(is_dir($dir."/".$filename)){
          $new_foldersize = foldersize($dir."/".$filename);
          $count_size = $count_size+ $new_foldersize;
        }else if(is_file($dir."/".$filename)){
          $count_size = $count_size + filesize($dir."/".$filename);
          $count++;
        }
   }
 }
return $count_size;
}

Call in Action

<?php
  $folder_name = "myFolder";
  echo folderSize($folder_name);
?>

Output

The above function will return the folder size in bytes. So we need to write another function which will convert the bytes to Kilobyte, Megabyte, Gigabyte, Terabyte etc.

PHP Function to format size

function sizeFormat($bytes){ 
$kb = 1024;
$mb = $kb * 1024;
$gb = $mb * 1024;
$tb = $gb * 1024;

if (($bytes >= 0) && ($bytes < $kb)) {
return $bytes . ' B';

} elseif (($bytes >= $kb) && ($bytes < $mb)) {
return ceil($bytes / $kb) . ' KB';

} elseif (($bytes >= $mb) && ($bytes < $gb)) {
return ceil($bytes / $mb) . ' MB';

} elseif (($bytes >= $gb) && ($bytes < $tb)) {
return ceil($bytes / $gb) . ' GB';

} elseif ($bytes >= $tb) {
return ceil($bytes / $tb) . ' TB';
} else {
return $bytes . ' B';
}
}

Call in Action

<?php
  $folder_name = "myFolder";
  echo sizeFormat(folderSize($folder_name));
?>
Top