Listing files of a directory and its subfolders with PHP

Published on 2024-02-12 • Modified on 2024-02-12

This snippet shows how to list files of a directory and its subfolders with PHP. There are several ways to achieve this goal, but we do it with the RecursiveDirectoryIterator SPL class in this snippet. In the following example, we list all PHP files in the src/Controller directory, which has three sub-folders: Admin, Post and Snippet.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet290Trait
{
    public function snippet290(): void
    {
        $baseDir = \dirname(__DIR__);
        $dir = new \RecursiveDirectoryIterator($baseDir);
        $flat = new \RecursiveIteratorIterator($dir);
        $files = new \RegexIterator($flat, '/\.php$/i');

        $count = 0;
        foreach ($files as $file) {
            /** @var \SplFileInfo $file */
            $pathName = $file->getPathname();
            $pathName = str_replace($baseDir.'/', '', $pathName); // remove base path
            ++$count;

            echo $pathName.PHP_EOL;
        }
        echo PHP_EOL;
        echo 'Number of files: '.$count;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!