Last active
June 24, 2021 11:54
-
-
Save sam-ngu/452557a867e4ec37d1263543916e31c5 to your computer and use it in GitHub Desktop.
PHP iterator to recursively iterate through a folder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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