开发者

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

I开发者_运维知识库 have a folder named files, how do I determine the sum of size of it's files?


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.


echo array_sum(array_map('filesize', glob('*')));


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”;
?>


if you have access to exec function you can use this code:

exec("du {directory_path_you_want_see_size} -s 2>&1",$output);
echo intval($output[0]) ;

example:

exec("du /home/ -s 2>&1",$output);
echo intval($output[0]) ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜