Edwin Rodríguez

Traverse directories on PHP


Iterate files excluding dots

foreach (new DirectoryIterator($dirname) as $file) {
    if($file->isDot()) continue;
    echo $file->getFilename();
}

Iterate filtering by extension

foreach (new DirectoryIterator($dirname) as $file) {
    if($file->getExtension() !== 'exe' ) continue;
    echo $file->getFilename();
}

Recursive Way

foreach ( new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dirname)) as $file ) {
  if ( $file->isFile() )
    $file->getPathname();
  }

The $file variable in the iteration is a DirectoryIterator class. See the documentation for useful functionalities.


2017 - Edwin Rodríguez