开发者

Echo the combined size of all files

I have this script which works except for one small problem. Basically it gets the total size of all file in a specified dir开发者_开发问答ectory 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.


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>';


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


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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜