How to get directory size in PHP

function GetDirectorySize($path){
    $bytestotal = 0;
    $path = realpath($path);
    if($path!==false && $path!='' && file_exists($path)){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
            $bytestotal += $object->getSize();
        }
    }
    return $bytestotal;
}

The same idea as Janith Chinthana suggested.
With a few fixes:

  • Converts $path to realpath
  • Performs iteration only if path is valid and folder exists
  • Skips . and .. files
  • Optimized for performance

Leave a Comment