php – directory size

I was trying to get a directory size with PHP under a *nix environment…
This is what I’v found on stackoverflow… and it works 🙂

 * Get the directory size
 * @param directory $directory
 * @return integer
function dirSize($directory) {
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
    return $size;

And to get it with Kb, Mb, Gb etc….

 function formatSizeUnits($bytes)
        $symbols = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        $exp = floor(log($bytes) / log(1024));
        @$bytes = sprintf('%.2f ' . $symbols[$exp], ($bytes / pow(1024, floor($exp))));
        return $bytes;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.