Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

recursion - Recursively counting files with PHP

Simple question for a newb and my Google-Fu is failing me. Using PHP, how can you count the number of files in a given directory, including any sub-directories (and any sub-directories they might have, etc.)? e.g. if directory structure looks like this:

/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

The script should return with '5' for "./Dir_A".

I've cobbled together the following but it's not quite returning the correct answer, and I'm not sure why:

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; }

I'd greatly appreciate any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should do the trick:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...