<?php
// Script to return current directory size, including sum of sub directories

// Functions defined 
// function to get file names
if (!function_exists("scandir"))
{  // php.net/scandir (PHP5) This function exists in ver 5
    function scandir($dirstr)
    { 
        $files = array();
        $fh = opendir($dirstr);
        while (false !== ($filename = readdir($fh)))
        {
            array_push($files, $filename);
        }
        closedir($fh);
        sort($files);
        return $files;
    }
}
// file size returns the size of a file or directory, sub directories are
// included in the size of a directory recursively but into one amount
function exefilesize ($filename)
{
    if ( is_dir($filename) )
    {
        $filesize = exedirsize("$filename");
    } else {
        $filesize = filesize($filename);
    }
    return $filesize;
}
// size of a directory uses both scandir and exefilesize to dig down and return
// a single size
function exedirsize($dirname)
{
    // in case of empty directory - best to set size to zero 
    $dirsize = 0;
    $dirscanlist = scandir("$dirname");
    foreach ($dirscanlist as $dirfilename)
    {
        // need to avoid infinite loop of current directory ie . and .. files
        if ( $dirfilename != '.' and $dirfilename != '..' )
        {
            $dirsize += exefilesize("$dirname/$dirfilename"); 
        }
    }
    return $dirsize;
}

// the current working directory is assumed as the required directory
$cwd = getcwd();
$dirsize = exefilesize("$cwd");
// return the size formatted with thousands, millions,...

// Method A: display the space used 
echo number_format($dirsize);

// Method B: do NOT show the space, use $dirsize in script to show it
// for method B comment out the echo statement and see dirsample.php
// echo number_format($dirsize);
?>

