DEV Community

Cover image for List files from directory with PHP
Wallace Maxters
Wallace Maxters

Posted on • Originally published at wallacemaxters.com.br

List files from directory with PHP

In PHP, you can list a directory using the class RecursiveDirectoryIterator.

View the follow code:

$dir = __DIR__ . '/folder';

$directory_iterator = new RecursiveDirectoryIterator(
    $dir, 
    FilesystemIterator::SKIP_DOTS
);

$iterator = new RecursiveIteratorIterator($directory_iterator);

foreach ($iterator as $file) {
    echo $file, "\n";
}
Enter fullscreen mode Exit fullscreen mode

If you need sort the file list, you can convert the directory iterator instance to array and use the ksort function.

View bellow:


$dir = __DIR__ . '/folder';

$iterator = new RecursiveIteratorIterator(
  new RecursiveDirectoryIterator(
      $dir, 
      FilesystemIterator::SKIP_DOTS
  )
);

$array = iterator_to_array($iterator);

ksort($array);

foreach ($array as $file) {
  echo $file, "\n";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)