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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

its returning an empty array. :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.