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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With