How to get Folder or Directory size in PHP Laravel?

How to get Folder or Directory size in PHP Laravel?

In this tutorial, i am going to tell you how to get directory size in PHP Laravel.

As all knows, PHP has inbuilt function to get file size using filesize() method but ever you think how to get directory size in PHP or how to read directory files and sub directory within directory?

A folder may have many files and have subfolder that contains many files too.

So here you will know how to iterate over folders and their files.

PHP function will return size in bytes so first we write a function to convert bytes to Kilobyte, Megabyte, Gigabyte and Terabyte etc.

PHP Function to format size
  1. function formatSize($bytes){
  2. $kb = 1024;
  3. $mb = $kb * 1024;
  4. $gb = $mb * 1024;
  5. $tb = $gb * 1024;
  6. if (($bytes >= 0) && ($bytes < $kb)) {
  7. return $bytes . ' B';
  8. } elseif (($bytes >= $kb) && ($bytes < $mb)) {
  9. return ceil($bytes / $kb) . ' KB';
  10. } elseif (($bytes >= $mb) && ($bytes < $gb)) {
  11. return ceil($bytes / $mb) . ' MB';
  12. } elseif (($bytes >= $gb) && ($bytes < $tb)) {
  13. return ceil($bytes / $gb) . ' GB';
  14. } elseif ($bytes >= $tb) {
  15. return ceil($bytes / $tb) . ' TB';
  16. } else {
  17. return $bytes . ' B';
  18. }
  19. }

Now we will write a function to scan directory and return size of directory.

PHP Function to return directory size
  1. function folderSize($dir){
  2. $total_size = 0;
  3. $count = 0;
  4. $dir_array = scandir($dir);
  5. foreach($dir_array as $key=>$filename){
  6. if($filename!=".." && $filename!="."){
  7. if(is_dir($dir."/".$filename)){
  8. $new_foldersize = foldersize($dir."/".$filename);
  9. $total_size = $total_size+ $new_foldersize;
  10. }else if(is_file($dir."/".$filename)){
  11. $total_size = $total_size + filesize($dir."/".$filename);
  12. $count++;
  13. }
  14. }
  15. }
  16. return $total_size;
  17. }
Define Folder and pass it to function to get size
  1. $folder_path = "folder path";
  2. echo formatSize(folderSize($folder_path));

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort serdivan escort sapanca escort karasu escort hendek escort ankara escort
sakarya escort kızlar sakarya escort kaliteli sakarya escort vip sakarya escort elit sakarya escort bayan sakarya escort adresleri.