Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Most efficient way to get the number of files within a directory

Tags:

php

Consider these two folder structures:

Foo/
    Folder1/
        File1.txt
    Folder2/
    Folder3/
    File2.txt

Bar/
    Folder1/
        Folder2/
    Folder3/
    Folder4/

I'd like to know the most efficient way in PHP to tell me that the "Foo" folder has two files in it and that the "Bar" folder has zero files in it. Notice that it's recursive. Even though the "File1.txt" file is not immediately inside the "Foo" folder, I still want it to count. Also, I don't care what the names of the files are. I just want the total number of files.

Any help would be appreciated. Thanks!

like image 267
Nick Avatar asked Dec 11 '25 13:12

Nick


2 Answers

Use RecursiveDirectoryIterator. Here is the documentation.

$rdi = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/home/thrustmaster/Temp', FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY);

foreach ($rdi as $file)
    echo "$file\n";
print iterator_count($rdi);
like image 103
UltraInstinct Avatar answered Dec 13 '25 03:12

UltraInstinct


You need a recursive function to loop through the directory structure. That's all you can really do to count the number of files without going with object orientated solution.

This function will recursively count the number of files in a directory and it's sub-directories.

function countDir($dir, $i = 0) {
    if ($handle = opendir($dir.'/')) {
        while (false !== ($file = readdir($handle))) {

            // Check for hidden files the array[0] on a 
            // string returns the first character
            if ($file[0] != '.') {
                if (is_dir($dir.'/'.$file)) {
                    $i += countDir($dir.$file, $i);
                } else {
                    $i++;
                }
            }
        }
    }

    return $i;
}
like image 41
Jordan Shute Avatar answered Dec 13 '25 02:12

Jordan Shute



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!