Search code examples
phpfilesizeopendir

Calculate the weight of a directory (folder) in php


I am wanting to calculate the weight of a directory in php, then display the data as per the example below.

Example:

Storage
50 GB (14.12%) of 353 GB used

I have the following function, with which I show in a list the folders that are inside the root.

<?php

    $dir = ('D:\data');
    echo "Size : " Fsize($dir);
    function Fsize($dir)
        {
            if (is_dir($dir))
                {
                    if ($gd = opendir($dir))
                        {
                            $cont = 0;
                            while (($file = readdir($gd)) !== false)
                                {
                                    if ($file != "." && $file != ".." )
                                        {
                                            if (is_dir($file))
                                                {
                                                    $cont += Fsize($dir."/".$file);
                                                }
                                            else
                                                {
                                                    $cont += filesize($dir."/".$file);
                                                    echo  "file : " . $dir."/".$file . "&nbsp;&nbsp;" . filesize($dir."/".$file)."<br />";
                                                }
                                        }
                                }
                            closedir($gd);
                        }
                }
            return $cont;
        }

?>

The size it shows me of the folder is 3891923, but it is not the real size, when validating the directory the real size is 191791104 bytes

Can you help me, please?


Solution

  • Your test for directory is incorrect here:

    if (is_dir($file))   // This test is missing the directory component
         {
         $cont += Fsize($dir."/".$file);
         }
    else
    

    Try:

    if (is_dir("$dir/$file"))   // This test adds the directory path
         {
         $cont += Fsize($dir."/".$file);
         }
    else
    

    PHP offers a number of iterators that can simplify operations like this:

    $path = "path/to/folder";
    $Directory = new RecursiveDirectoryIterator($path);
    $Iterator = new RecursiveIteratorIterator($Directory);
    $Iterator->setFlags(FilesystemIterator::SKIP_DOTS);
    
    $totalFilesize = 0;
    foreach($Iterator as $file){
        if ($file->isFile()) {
            $totalFilesize += $file->getSize();
        }
    }
    
    echo "Total: $totalFilesize";