Skip to content

PHP function – directory_size()

Here’s a quick PHP function that will return the size of all files in a directory.

To use: pass the directory you want to check as the only variable, eg: directory_size(“/home/web/directory”)

function directory_size($dir)
/*	Return the file size for files in directory
	
	Inputs:
		$dir	The directory to check
	Outputs:
		The total file size of all files in $dir
	*/
	{
	$retval = 0;
	$dirhandle = opendir($dir);
	while ($file = readdir($dirhandle))
		{
		if ($file!="." && $file!="..")
			{
			if (is_dir($dir."/".$file))
				{
				$retval = $retval + directory_size($dir."/".$file);
				}
			else
				{
				$retval = $retval + filesize($dir."/".$file);
				}
			}		
		}
	closedir($dirhandle);

	return $retval;
	}

Note that the function calls itself recursively so all subdirectories are included in the total.

To get it in a little more human friendly format, I use the following code.

$total_file_size = directory_size("/directory");
$file_size_suffix = "bytes";
if ($total_file_size>1024)
	{
	$file_size_suffix = "kb";
	$total_file_size = $total_file_size / 1024;
	}
if ($total_file_size>1024)
	{
	$file_size_suffix = "mb";
	$total_file_size = $total_file_size / 1024;
	}
$total_file_size = number_format($total_file_size, 2)." ".$file_size_suffix;

This will take ‘82358432’ and change it to ‘78.54 mb’. And if you’re dealing with really large directories, it would be simple to extend it beyond megabytes by dividing by 1024 as many times as needed to get to the unit you’re after.

Credit: This script is loosely based on this one at alt-php-faq.org.

Published inProgramming

One Comment

  1. Turns out there’s a pretty significant issue with this function. It doesn’t scale well at all. I’ve had a few users report pages timing out and it’s due to this function hacking its way through folders with 10,000 files plus. Guess I’ll need to work out something better. Maybe shelling to du /folder/ and parsing the results will do the job when the server allows it.

Leave a Reply

Your email address will not be published. Required fields are marked *