Peter
Peter

Reputation: 215

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.

Upvotes: 1

Views: 836

Answers (2)

vincenth
vincenth

Reputation: 1792

Since you are using RecursiveDirectoryIterator, you should take a look at globiterator which helps you traversing directory and matching files.

EDIT: As stated in the documentation :

Iterates through a file system in a similar fashion to glob().

You can easily loop through the files matching a pattern :

$it = new GlobIterator('./*/*.txt');
foreach($it as $item){
    var_dump($item->getFilename());
}

Upvotes: 0

Somebody
Somebody

Reputation: 11

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

?>

Upvotes: 1

Related Questions