2

I want not scan all the files in a directory and its sub-directory. And get their path in an array. Like path to the file in the directory in array will be just

path -> text.txt

while the path to a file in sub-directory will be

somedirectory/text.txt

I am able to scan single directory, but it returns all the files and sub-directories without any ways to differentiate.

    if ($handle = opendir('fonts/')) {
    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry<br/>";
    }


    closedir($handle);
    }

What is the best way to get all the files in the directory and sub-directory with its path?

Jørgen R
  • 10,568
  • 7
  • 42
  • 59
esafwan
  • 17,311
  • 33
  • 107
  • 166

2 Answers2

8

Using the DirectoryIterator from SPL is probably the best way to do it:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach ($it as $file) echo $file."\n";

$file is an SPLFileInfo-object. Its __toString() method will give you the filename, but there are several other methods that are useful as well!

For more information see: http://www.php.net/manual/en/class.recursivedirectoryiterator.php

TimWolla
  • 31,849
  • 8
  • 63
  • 96
4

Use is_file() and is_dir():

function getDirContents($dir)
{
  $handle = opendir($dir);
  if ( !$handle ) return array();
  $contents = array();
  while ( $entry = readdir($handle) )
  {
    if ( $entry=='.' || $entry=='..' ) continue;

    $entry = $dir.DIRECTORY_SEPARATOR.$entry;
    if ( is_file($entry) )
    {
      $contents[] = $entry;
    }
    else if ( is_dir($entry) )
    {
      $contents = array_merge($contents, getDirContents($entry));
    }
  }
  closedir($handle);
  return $contents;
}
ComFreek
  • 29,044
  • 18
  • 104
  • 156