PHP Fetch All Files In A Directory

php

This is a PHP code snippet that will allow you to fetch all the files in a directory. This is useful if you want to loop through all the files in a directory and perform some action on them.

<?php
$dir = '/path/to/directory';
$files = scandir($dir);
$files = array_diff($files, array('.', '..'));
print_r($files);

The problem with this code is that it doesn't work recursively. If you want to fetch all the files in a directory and its subdirectories, you can use the following code:

<?php
function getFiles(string $directory)
{
    $directoryIterator = new \RecursiveDirectoryIterator($directory);
    $iterator = new \RecursiveIteratorIterator($directoryIterator);

    $files = [];
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $files[] = $file->getPathname();
        }
    }

    return $files;
}

If you want to limit this to a specific file extension, the $file variable will have a method called getExtension() which you can use to filter the files.

function isMarkdownFile($file): bool
{
    return $file->getExtension() === 'md';
}
$files = array_filter($files, 'isMarkdownFile');

This will only return files with the .md extension. You can change this to any extension you want.

Written on

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring