IT & Programming

Calculate size of a directory with PHP

Function accepts directory path as parameter and returns the total size of it. This function also considers all files and sub-folders of a directory for used space calculation.

Function

function dirSize($dir, $buf = 2) {

    static $buffer;
    if (isset($buffer[$dir]))
        return $buffer[$dir];
    if (is_file($dir))
        return filesize($dir);
    if ($dh = opendir($dir)) {
        $size = 0;
        while (($file = readdir($dh)) !== false) {
            if ($file == '.' || $file == '..')
                continue;
            $size+=dirsize($dir . '/' . $file, $buf - 1);
        }
        closedir($dh);
        if ($buf > 0)
            $buffer[$dir] = $size;
        return $size;
    }
    return false;
}

Then another function humanReadable() should be called over the result of dirSize Function. This function returns the human readable size of directory.

Function

function humanReadable($Bytes) {

    $Type = array("", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta");
    $Index = 0;
	
	while ($Bytes >= 1024) {
		$Bytes/=1024;
        $Index++;
    }
	
    return("" . $Bytes . " " . $Type[$Index] . "bytes");
}

Calling the function

// Size in bytes
$size=dirSize("D:/documents/photos");

// Size in human readable format
echo humanReadable($size);

Output

9.96 megabytes

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *