Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
Last active June 24, 2021 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam-ngu/452557a867e4ec37d1263543916e31c5 to your computer and use it in GitHub Desktop.
Save sam-ngu/452557a867e4ec37d1263543916e31c5 to your computer and use it in GitHub Desktop.
PHP iterator to recursively iterate through a folder.
<?php
$folderPath = __DIR__ . '/path/to/folder/';
try {
$dirIterator = new \RecursiveDirectoryIterator($folderPath);
/** @var \RecursiveDirectoryIterator | \RecursiveIteratorIterator $it */
$it = new \RecursiveIteratorIterator($dirIterator);
// the valid() method checks if current position is valid eg there is a valid file or directory at the current position
while ($it->valid()) {
// isDot to make sure it is not current or parent directory
if (! $it->isDot() && $it->isFile() && $it->isReadable()) {
// $file is a SplFileInfo instance
$file = $it->current();
$filePath = $it->key();
// do something about the file
// ...
require $filePath;
}
$it->next();
}
} catch (\Exception $e) {
throw $e;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment