DEV Community

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

Posted on • Originally published at wallacemaxters.com.br

3

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more