Echo the combined size of all files

2019-08-13 19:10发布

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.

4条回答
看我几分像从前
2楼-- · 2019-08-13 19:45

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

查看更多
贪生不怕死
3楼-- · 2019-08-13 19:57

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>';
查看更多
女痞
4楼-- · 2019-08-13 20:08

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

查看更多
不美不萌又怎样
5楼-- · 2019-08-13 20:10

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 /*")

查看更多
登录 后发表回答