Page 1 of 1

How to? Size of folder.

Posted: Thu Aug 21, 2003 5:51 am
by Czar
How can i count total size (in kb) of folder contents? I'm doing a script that prints a line in percents that describes how much space is left in folder. (% of max 50Mb). I thought it had something to do with filesize()-func? I did one, but didn't work well by looping all files in folder to var's and then summing them. Need help pls.

Thanks.

Posted: Thu Aug 21, 2003 6:05 am
by JayBird
Heres some code i have used. Easily modified for you needs.

The function foldersize calculate the size of the folder. A bar graph is drawn, using a simple image, just a 1x1 red dot, which is resized according to the size of the folder.

Code: Select all

<?php

function foldersize( $path )
{
  $size = 0;
  if( $dir = @opendir( $path )) {
    while(($file = readdir($dir)) !== false ) {
      if( is_dir( "$path/$file" ) && $file != '.' && $file != '..' ) {
        $size += foldersize( "$path/$file" );
      }
      if( is_file( "$path/$file" )) {
        $size += filesize( "$path/$file" );
      }
    }
    closedir($dir);
  }
  return $size;
}

$sizes['files'] = 0;
if( $dir = @opendir( '.' )) {
  while(($file = readdir($dir)) !== false ) {
    if( is_dir( "$file" ) && $file != '.' && $file != '..' ) {
      $sizes[$file] = foldersize( "$file" );
    }
    if( is_file( "$file" )) {
      $sizes['files'] += filesize( "$file" );
    }
  }
  closedir($dir);
}

$totsize = 0;
foreach( $sizes as $fsize ) {
  $totsize += $fsize;
}

echo "<table>";
foreach( $sizes as $key => $size ) {
  $perc = 100 * $size / $totsize;
  $width = 4 * $perc;
  $percstr = number_format( $perc, 1 ) . '%';
  $sizestr = number_format( $size );
  printf( '<tr><td>%s</td><td align="right">%s</td><td><img src="red_dot.gif" width="%s" ' .
    'height="10" border="0" alt="%s"> %s</td>', $key, $sizestr, $width, $percstr,$percstr ); 
}
echo "</table>";
?>
Mark