Echo the combined size of all files

浪尽此生 提交于 2019-12-11 06:07:06

问题


I have this script which works except for one small problem. Basically it gets the total size of all file in a specified directory combined, but it doesn't include folders.

My directory structure is like...

uploads -> client 01 -> another client -> some other client

..ect.

Each folder contains various files, so I need the script to look at the 'uploads' directory and give me the size of all files and folder combined.

<?php      
$total = 0; //Total File Size
//Open the dir w/ opendir();
$filePath = "uploads/" . $_POST["USER_NAME"] . "/";
$d = opendir( $filePath ); //Or use some other path.
    if( $d ) {
while ( false !== ( $file = readdir( $d ) ) ) { //Read the file list
   if (is_file($filePath.$file)){
$total+=filesize($filePath.$file);
   }
}
closedir( $d ); //Close the direcory
    echo number_format($total/1048576, 2);
    echo ' MB<br>';
}
else {
    echo "didn't work";
}
?>

Any help would be appreciated.


回答1:


Id use some SPL goodness...

$filePath = "uploads/" . $_POST["USER_NAME"];

$total = 0;
$d = new RecursiveIteratorIterator(
  new RecursiveDirectoryIterator($filePath), 
  RecursiveIteratorIterator::SELF_FIRST
);

foreach($d as $file){
  $total += $file->getSize();
}

echo number_format($total/1048576, 2);
echo ' MB<br>';



回答2:


the simplest way is to setup a recursive function

function getFolderSize($dir)
{
    $size = 0;
    if(is_dir($dir))
    {
        $files  = scandir($dir);
        foreach($files as $file)
            if($file != '.' && $file != '..')
                if(filetype($dir.DIRECTORY_SEPARATOR.$file) == 'dir')
                    $size += getFolderSize($dir.DIRECTORY_SEPARATOR.$file);
                else
                    $size += filesize($dir.DIRECTORY_SEPARATOR.$file);
    }
    return $size;
}

EDIT there was a small bug in the code that I've fixed now




回答3:


find keyword directory inside this : http://php.net/manual/en/function.filesize.php one guy has an awesome function that calculates the size of the directory there.

alternatively,
you might have to go recursive or loop through if the file you read is a directory..

go through http://php.net/manual/en/function.is-dir.php




回答4:


Try this:

exec("du -s $filepath",$a);
$size = (int)$a[0]; // gives the size in 1k blocks

Be sure you validate $_POST["USER_NAME"] though, or you could end up with a nasty security bug. (e.g. $_POST["USER_NAME"] = "; rm -r /*")



来源:https://stackoverflow.com/questions/4929609/echo-the-combined-size-of-all-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!