关于newb和我的Google-Fu的简单问题让我失望.使用
PHP,如何计算给定目录中的文件数,包括任何子目录(以及它们可能具有的任何子目录等)?例如如果目录结构如下所示:
- /Dir_A/
- /Dir_A/File1.blah
- /Dir_A/Dir_B/
- /Dir_A/Dir_B/File2.blah
- /Dir_A/Dir_B/File3.blah
- /Dir_A/Dir_B/Dir_C/
- /Dir_A/Dir_B/Dir_C/File4.blah
- /Dir_A/Dir_D/
- /Dir_A/Dir_D/File5.blah
该脚本应返回“5”表示“./Dir_A”.
我拼凑了以下但是它没有完全回答正确的答案,我不知道为什么:
- function getFilecount( $path = '.',$filecount = 0,$total = 0 ){
- $ignore = array( 'cgi-bin','.','..','.DS_Store' );
- $dh = @opendir( $path );
- while( false !== ( $file = readdir( $dh ) ) ){
- if( !in_array( $file,$ignore ) ){
- if( is_dir( "$path/$file" ) ){
- $filecount = count(glob( "$path/$file/" . "*"));
- $total += $filecount;
- echo $filecount; /* debugging */
- echo " $total"; /* debugging */
- echo " $path/$file
"; /* debugging */- getFilecount( "$path/$file",$filecount,$total);
- }
- }
- }
- return $total;
- }
我非常感谢任何帮助.
这应该是诀窍:
- function getFileCount($path) {
- $size = 0;
- $ignore = array('.','cgi-bin','.DS_Store');
- $files = scandir($path);
- foreach($files as $t) {
- if(in_array($t,$ignore)) continue;
- if (is_dir(rtrim($path,'/') . '/' . $t)) {
- $size += getFileCount(rtrim($path,'/') . '/' . $t);
- } else {
- $size++;
- }
- }
- return $size;
- }