Best Practice to Calculate Directory Size in PHP – PHP Tutorial

By | July 31, 2019

To calculate a directory size in php, there are some methods:

1.If you are using windows system, you can use php to parse dir command. Meanwhile, if your pc is linux, you also can parse du command.

directory

2.Iterate size of all files in this directory and sum them.

In this tutorial, we will introduce using method 2 to calculate a directory size using php.

Calculate direcotry size

function folderSize($dir){
	$count_size = 0;
	$count = 0;
	try{
		$dir_array = @scandir($dir);
		if (empty($dir_array)) return $count_size;
		foreach($dir_array as $key=>$filename){
			if($filename!=".." && $filename!="."){
				$path = $dir.DIRECTORY_SEPARATOR.$filename;
				
				if(is_dir($path)){
					$new_foldersize = foldersize($path);
					$count_size = $count_size+ $new_foldersize;
				}else if(is_file($path)){
					$count_size = $count_size + filesize($path);
					$count++;
				}
			 }
	   }
	   unset($dir_array);
	}
	catch(Exception $e){
	}
	return $count_size;
}

Format output

function formatSize( $bytes )
{
	$types = array( 'B', 'KB', 'MB', 'GB', 'TB' );
	for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
			return( round( $bytes, 2 ) . " " . $types[$i] );
}

How to use?

echo (formatSize(folderSize("E:"));

However, there is one thing you must notice:

If the path of a directory or file contains some unicode characters, such as chinese. This method is not correct.

 

Category: PHP

Leave a Reply