Wednesday, June 4, 2008

Directory Size Calculations with Code Examples

Calculating files are easy. Using the php filesize() function, you can easily find out the file size. However, have you encountered a case whereby you need to calculate the whole directory, including sub folders and the files in them?

In this article, we are going to talk about how to recursively calculate the total folder size of a directory. You can add thousands of folders and millions of files into a single folder, and this customized php function is able to calculate out the size of the directory. You can also use it for calculating your disk space too!

function dirsize($dirname) {
if (!is_dir($dirname) || !is_readable($dirname)) {
// check whether the directory is valid.
return false;

$dirname_stack[] = $dirname;
$size = 0;

do {
$dirname = array_shift($dirname_stack);
$handle = opendir($dirname);
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_readable($dirname . DIRECTORY_SEPARATOR . $file)) {
if (is_dir($dirname . DIRECTORY_SEPARATOR . $file)) {
$dirname_stack[] = $dirname . DIRECTORY_SEPARATOR . $file;
$size += filesize($dirname . DIRECTORY_SEPARATOR . $file);
} while (count($dirname_stack) > 0);

return $size;

Hope this helps you in building it in as a useful function in your administration panel of your website.

Link to code example on pastebin:

No comments: