This article brings you the content is about how PHP uses recursion to calculate the size of all files in a directory (code), there is a certain reference value, the need for friends can refer to, I hope to help you.
sudo find/private/etc-exec ls-l {} \; | awk ' BEGIN {sum=0} {sum+=$5;} END {print sum} ' # 4947228ls-ld/etc #/etc-private/etc
First calculate the size of all files in/etc directory 4947228
dirutil.php
<?php/** * Created by Phpstorm. * USER:MCH * DATE:8/14/18 * time:22:11 */class dirutil {public static function GetSize (string $path) {$tota lsize = 0; $path = Realpath ($path); if (!file_exists ($path)) {return $totalSize; } if (!is_dir ($path)) {return filesize ($path); if ($dh = Opendir ($path)) {while (($file = Readdir ($DH))!== false) {if ($file!== ". "&& $file!==") {$abs = $path. Directory_separator. $file; if (Is_dir ($file)) {$totalSize + = Self::getsize ($abs); } else {$totalSize + = FileSize ($abs); }}} closedir ($DH); } return $totalSize; public static function Entryforeach (string $path, callable $callback, mixed $data = null) {$path = Realpath ($ path); if (!file_exisTS ($path)) {return 0; } if (!is_dir ($path)) {return Call_user_func ($callback, $path, $data); if ($dh = Opendir ($path)) {while (($file = Readdir ($DH))!== false) {if ($file!== ". "&& $file!==") {$abs = $path. Directory_separator. $file; if (Is_dir ($file)) {Self::entryforeach ($abs, $callback, $data); } else {Call_user_func ($callback, $abs, $data); }}} closedir ($DH); } return 0; public static function Entryreduce (string $path, callable $callback, $init) {$ACC = $init; $path = Realpath ($path); if (!file_exists ($path)) {return $ACC; } if (!is_dir ($path)) {return Call_user_func ($callback, $ACC, $path); } if ($dh = Opendir ($path)) {WHIle (($file = Readdir ($DH))!== false) {if ($file!== "." && $file!== "..") {$abs = $path. Directory_separator. $file; if (Is_dir ($file)) {$ACC = Self::entryreduce ($abs, $callback, $ACC); } else {$acc = Call_user_func ($callback, $ACC, $abs); }}} closedir ($DH); } return $ACC; }}
Test
PHP./DIRUTIL.PHP/ETCIF ($ARGC < 2) { printf ("usage:php%s [filename]\n", __file__); Exit (1);} Echo Dirutil::getsize ($argv [1]). Php_eol; 899768$dir_get_size = function ($path) { $size = 0; Dirutil::entryforeach ($path, function ($path) use (& $size) { $size + = FileSize ($path); }); return $size;}; echo $dir _get_size ($argv [1]). Php_eol; 899768echo dirutil::entryreduce ($argv [1], function ($sum, $path) { $sum + = FileSize ($path); return $sum;}, 0). Php_eol; 899768