QRdvark.com

We all know how to get the size of a file with PHP, but what if you want to get the size of an entire directory, including all its sub directories. Here the PHP SPL recursive directory iterator comes into play as it traverses the directory tree recursively and gives us the size of all files in it. Then we simply total the sizes and return the result.


<?php

/**
 *
 * @get size of a directory in bytes
 *
 * @param string $directory
 *
 * @return int
 *
 */
function directorySize($directory)
{
    
$size 0;
    foreach(new 
RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file)
    {
        
$size += $file->getSize();
    }
    return 
$size;
}

/*** example implementation ***/
$directory '/home/foo';
$size directorySize($directory);
echo 
$size;

?>