How to? Size of folder.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Czar
Forum Commoner
Posts: 58
Joined: Sun Dec 29, 2002 11:17 am

How to? Size of folder.

Post 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.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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
Post Reply