CodingHowTo

List Files in a Directory (Recursive, Filtered)

List Files in a Directory (Recursive, Filtered) in PHP

Content

To list files in a directory recursively and apply filters, we can use a combination of PHP's glob function and recursive iteration. The following example demonstrates how to achieve this:


<?php

function listFilesRecursively($directory, $filter = '*') {
    $files = [];
    foreach (glob($directory . '/' . $filter) as $file) {
        if (is_dir($file)) {
            $files = array_merge($files, listFilesRecursively($file, $filter));
        } else {
            $files[] = $file;
        }
    }
    return $files;
}

$directoryPath = '/path/to/directory';
$fileFilter = '*.php'; // Filter for PHP files

$files = listFilesRecursively($directoryPath, $fileFilter);

foreach ($files as $file) {
    echo $file . "
"; } ?>

In the above code:

  • The listFilesRecursively function takes two parameters: the directory path and an optional file filter (defaulting to '*').
  • It uses glob to retrieve files that match the filter within the specified directory.
  • If a file is a directory, the function calls itself recursively to list its contents.
  • The function returns an array of file paths.

To use this function, specify the path to your target directory and the desired file filter. In the example above, we are filtering for PHP files using the '*.php' pattern.

Conclusion

Recursively listing files in a directory with filters is a powerful tool for file management and analysis. Using PHP's built-in functions like glob and recursive iteration, you can efficiently retrieve specific files based on your needs. This technique is particularly useful when working with large or complex file structures, allowing you to focus on the files that matter most.