5

For looping all files in a directory, I created this code in php :

$dir = new DirectoryIterator(dirname(__FILE__));
$files = scandir($dir.'/');
foreach($files as $file) 
{
    echo $file;
    echo "\n";
}

However I am not able to list all files inside multiple subdirectory of a directory.

hakre
  • 193,403
  • 52
  • 435
  • 836
Esha Soni
  • 51
  • 2
  • Is __FILE___ a relative path from the current directory? Is so take of the ending '/' in the scandir – Kyle Johnson Dec 21 '12 at 17:02
  • 2
    did you check this : http://stackoverflow.com/questions/7121479/listing-all-the-folders-subfolders-and-files-in-a-directory-using-php – Oussama Jilal Dec 21 '12 at 17:04
  • @kyle: `__FILE__` is a [magic constant](http://php.net/manual/en/language.constants.predefined.php), if that's what you're asking. – Brad Christie Dec 21 '12 at 17:04

3 Answers3

5

Use RecursiveDirectoryIterator

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
    echo "$name\n";
}

?>
GBD
  • 15,847
  • 2
  • 46
  • 50
0

Try this instead. See this in php manual

function loop_dir($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
                                              RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $path) {
      echo $path
    }
}
DWright
  • 9,258
  • 4
  • 36
  • 53
0

Simple as this:

$dir = dir('DIRECTORY_TO_DISPLAY_HERE');
while (($file = $dir->read()) !== false) {
    if ($file != '..' && $file != '.') {
        echo $file;
    }
}
$dir->close();
step
  • 2,254
  • 2
  • 23
  • 45