使用PHP递归计数文件

前端之家收集整理的这篇文章主要介绍了使用PHP递归计数文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
关于newb和我的Google-Fu的简单问题让我失望.使用 PHP,如何计算给定目录中的文件数,包括任何子目录(以及它们可能具有的任何子目录等)?例如如果目录结构如下所示:
  1. /Dir_A/
  2. /Dir_A/File1.blah
  3. /Dir_A/Dir_B/
  4. /Dir_A/Dir_B/File2.blah
  5. /Dir_A/Dir_B/File3.blah
  6. /Dir_A/Dir_B/Dir_C/
  7. /Dir_A/Dir_B/Dir_C/File4.blah
  8. /Dir_A/Dir_D/
  9. /Dir_A/Dir_D/File5.blah

该脚本应返回“5”表示“./Dir_A”.

我拼凑了以下但是它没有完全回答正确的答案,我不知道为什么:

  1. function getFilecount( $path = '.',$filecount = 0,$total = 0 ){
  2. $ignore = array( 'cgi-bin','.','..','.DS_Store' );
  3. $dh = @opendir( $path );
  4. while( false !== ( $file = readdir( $dh ) ) ){
  5. if( !in_array( $file,$ignore ) ){
  6. if( is_dir( "$path/$file" ) ){
  7. $filecount = count(glob( "$path/$file/" . "*"));
  8. $total += $filecount;
  9. echo $filecount; /* debugging */
  10. echo " $total"; /* debugging */
  11. echo " $path/$file
    "; /* debugging */
  12. getFilecount( "$path/$file",$filecount,$total);
  13. }
  14. }
  15. }
  16. return $total;
  17. }

我非常感谢任何帮助.

这应该是诀窍:
  1. function getFileCount($path) {
  2. $size = 0;
  3. $ignore = array('.','cgi-bin','.DS_Store');
  4. $files = scandir($path);
  5. foreach($files as $t) {
  6. if(in_array($t,$ignore)) continue;
  7. if (is_dir(rtrim($path,'/') . '/' . $t)) {
  8. $size += getFileCount(rtrim($path,'/') . '/' . $t);
  9. } else {
  10. $size++;
  11. }
  12. }
  13. return $size;
  14. }

猜你在找的PHP相关文章