Directory Size

Discussion in 'PHP' started by kalle437, Jan 14, 2007.

  1. #1
    Hello!
    I wonder if anyone knows how to get the total size of all files in a specified directory to a variable.

    Kalle :)
     
    kalle437, Jan 14, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    
    $dir = 'some_dir/*';
    
    $size = array_sum(array_map('filesize', glob($dir)));
    
    echo $size;
    
    
    PHP:
    Untested.


    EDIT:

    And you can use this to get the size of the subdirs as well.

    
    
    function get_dir_size($directory, $subdirs = true)
    {
    	$files = glob($directory .'*');
    	$totalsize = 0;
    	
    	foreach ($files AS $file)
    	{
    		if ($subdirs AND is_dir($file))
    		{
    			$totalsize += get_dir_size($file .'/');
    		}
    		else
    		{
    			$totalsize += filesize($file);
    		}
    	}
    	
    	return $totalsize;
    } 
    
    
    echo get_dir_size('some-dir/');
    
    PHP:
     
    nico_swd, Jan 14, 2007 IP
  3. kalle437

    kalle437 Peon

    Messages:
    283
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks a lot. I found another script that I am using though. It is the following:

    
     
     <?php
    function getDirSize( $path ) {
       $totsize = 0;
       $dp = opendir( $path );
       while( $child = readdir( $dp ) ) {
          if( $child == '.' || $child == '..' ) continue;
     
          if( is_dir( $path . '/' . $child ) ) {
             $totsize += getDirSize( $path . '/' . $child );
          } else {
             $totsize += filesize( $path . '/' . $child );
          }
       }
       return $totsize;
    }
     
    
    $totalsize = 0;
    $totalsize = round((getDirSize('images')/1024)/1024, 2);
    echo $totalsize;
    
    ?>
    
    Code (markup):
     
    kalle437, Jan 14, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    This line:
    
    while( $child = readdir( $dp ) ) {
    
    PHP:
    Should look like this:
    
    while( ( $child = readdir( $dp ) ) !== false )
    
    PHP:
    http://us2.php.net/readdir
     
    nico_swd, Jan 14, 2007 IP
  5. kalle437

    kalle437 Peon

    Messages:
    283
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Ok, whats the difference? It is working excellent now! :D
     
    kalle437, Jan 14, 2007 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    Check the link I posted.

     
    nico_swd, Jan 14, 2007 IP