Get Folder or Directory size in PHP

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 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 the function:

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


Leave a Reply

Your email address will not be published. Required fields are marked *