Peter Peter - 3 months ago 12
PHP Question

Scanning directories and getting all files in PHP

My problem is, that I've got 4 directories:

/dir1/
/dir2/
/dir3/
/dir4/


which may contain any number of subdirectories, for example:

/dir1/
/subdir1/
/subdir2/

/dir2/
/subdir1/
/subdir2/
/subdir3/

/dir3/
/subdir1/

/dir4/
/subdir1/
/subdir2/
/subdir3/


These subdirectories, may contain any number of .txt files, for example:

/dir1/
/subdir1/
/1.txt
/2.txt
/subdir2/
/1.txt

/dir2/
/subdir1/
/1.txt
/subdir2/
/1.txt
/2.txt
/subdir3/
/1.txt

/dir3/
/subdir1/
/1.txt
/2.txt

/dir4/
/subdir1/
/1.txt
/subdir2/
/1.txt
/subdir3/
/1.txt
/2.txt
/3.txt


The problem is to find these .txt files in an automated way.

Impartant: There are only 2 levels of directories, as it's shown above.
I've managed to get so far:

/Applications/MAMP/htdocs/test/public/dir1/.
/Applications/MAMP/htdocs/test/public/dir1/..
/Applications/MAMP/htdocs/test/public/dir1/subdir1/1.txt
/Applications/MAMP/htdocs/test/public/dir1/subdir1/1.txt
/Applications/MAMP/htdocs/test/public/dir1/subdir2/1.txt
/Applications/MAMP/htdocs/test/public/dir1/subdir2/1.txt


With:

$path = realpath('/dir1');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename) {
$files[] = $filename;
}

for ($i=0; $i < count($files); $i++) {
echo $files[$i] . "<br>";
}


An array of paths, such as
array(sub1/1.txt, sub1/2.txt, sub2/1.txt ...)
would also be appreciated.
Any help is welcome.

Answer

Do you mean something like this?

UPDATE

<?php

function scanDirectory($directory) {

    $files = glob($directory . '/*');

    $data = array();
    foreach ($files as $file) {
        if (is_dir($file)) {
            $data = array_merge($data, scanDirectory($file));
        } else if (substr($file,-4) == '.txt') {
            $data[] = $file;
        }
    }

    return $data;
}

$startDirectory = realpath(__DIR__);

$data = scanDirectory($startDirectory);

var_dump($data);

?>