Get Total Directory Size In PHP

Overview – Get Total Directory Size In PHP

In my previous article called Get and Display Hard Disk Space Usage Using PHP I demonstrated how you can fetch and display the size of a hard disk as well as the free space and used space and display it to the user. While this works well it still doesn’t show how to get the size of a specific folder using PHP.

Get total directory size in PHP

Below I have created an example showing an alternate method to get total directory size in PHP. It makes use of the shell command du -sh (disk usage) and then uses a regular expression to fetch just the number of bytes out of the output generated by the du command.


// we need the full path to the folder we want to find the size of
//	below we result in a folder path of /var/www/mywebsite/html/files
$folder = $_SERVER['DOCUMENT_ROOT'].'/files';

// now prevent malicious attacks since we are executing a shell command
$folder = escapeshellcmd($folder);

// make sure this is a folder
if( ! is_dir($folder) )
	echo "$folder is not a folder.<br />";
// if we could find the pattern of our command du -s
	// we execute du (disk usage) to find out the folder size
	//	notice we use the execution operator (the key to the left of 1 on your keyboard)
	//	this is the same as the php function shell_exec()
	//	you can add the -h flaf to the below command to format the file size into MB, GB, etc.
	//		i.e. `du -sh $folder`;
	$output = `du -s $folder`;

	if( preg_match('/([0-9]+)(t.*)/',$output,$match) )
		$size = $match[1];

		// $size will now hold the size of the folder
		echo "Folder $folder is $size bytes<br />";
		// error
		// either we can't execute du -s command (such as windows users) or the folder doesn't exist
		echo "Error fetching folder size, are you on Linux? and can you execute commands?<br />";