Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i want get the sum of files size in folder by php

Tags:

php

I have a folder named files, how do I determine the sum of size of it's files?

like image 355
Mostafa Elkady Avatar asked May 07 '10 11:05

Mostafa Elkady


3 Answers

With DirectoryIterator and SplFileInfo

$totalSize = 0;
foreach (new DirectoryIterator('/path/to/dir') as $file) {
    if ($file->isFile()) {
        $totalSize += $file->getSize();
    }
}
echo $totalSize;

and in case you need that including subfolders:

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('/path/to/dir')
);

$totalSize = 0;
foreach ($iterator as $file) {
    $totalSize += $file->getSize();
}
echo $totalSize;

And you can run $totalSize through the code we gave you to format 6000 to 6k for a more human readable output. You'd have to change all 1000s to 1024 though.

like image 198
Gordon Avatar answered Sep 16 '22 18:09

Gordon


echo array_sum(array_map('filesize', glob('*')));
like image 22
Sjoerd Avatar answered Sep 19 '22 18:09

Sjoerd


Well try this using filesize() to calculate file size while iterating through all the files and sub-directory files.

<?php
function get_dir_size($dir_name){
    $dir_size =0;
    if (is_dir($dir_name)) {
        if ($dh = opendir($dir_name)) {
           while (($file = readdir($dh)) !== false) {
              if($file !=”.” && $file != “..”){
                  if(is_file($dir_name.”/”.$file)){
                      $dir_size += filesize($dir_name.”/”.$file);
                  }
                 /* check for any new directory inside this directory */
                 if(is_dir($dir_name.”/”.$file)){
                     $dir_size +=  get_dir_size($dir_name.”/”.$file);
                  }
               }
           }
        }
    }
closedir($dh);
return $dir_size;
}

$dir_name = “directory name here”;
/* 1048576 bytes == 1MB */
$total_size= round((get_dir_size($dir_name) / 1048576),2) ;
print “Directory $dir_name size : $total_size MB”;
?>
like image 37
frady Avatar answered Sep 19 '22 18:09

frady