This article introduces how PHP calculates the size of a directory (how many kb, how many megabytes). It mainly uses the filesize function and the recursive function to achieve this. Friends in need can refer to the source code of this article.
php uses recursion to calculate the directory size, mainly using the filesize function and the recursive function. The specific implementation source code is as follows:
<?php /* 作者: http://www.manongjc.com/article/28.html */ function directory_size($directory) { $directorySize=0; if ($dh = @opendir($directory)) { while (($filename = readdir ($dh))) { if ($filename != "." && $filename != "..") { if (is_file($directory."/".$filename)){ $directorySize += filesize($directory."/".$filename); } if (is_dir($directory."/".$filename)){ $directorySize += directory_size($directory."/".$filename); } } } } @closedir($dh); return $directorySize; } $directory = "./"; $totalSize = round((directory_size($directory) / 1024), 2); echo "Directory $directory: ".$totalSize. "kb."; ?>