Last active
February 10, 2021 21:01
-
-
Save magnetikonline/10612342 to your computer and use it in GitHub Desktop.
PHP reading of sub directories for files using recursion and generators.
This file contains hidden or 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 | |
// using generators (yield) to recursively read files from a source path | |
// more: http://www.php.net/manual/en/language.generators.php | |
foreach (readFileSubDir('~/testdir') as $fileItem) { | |
echo($fileItem . "\n"); | |
} | |
function readFileSubDir($scanDir) { | |
$handle = opendir($scanDir); | |
while (($fileItem = readdir($handle)) !== false) { | |
// skip '.' and '..' | |
if (($fileItem == '.') || ($fileItem == '..')) continue; | |
$fileItem = rtrim($scanDir,'/') . '/' . $fileItem; | |
// if dir found call again recursively | |
if (is_dir($fileItem)) { | |
foreach (readFileSubDir($fileItem) as $childFileItem) { | |
yield $childFileItem; | |
} | |
} else { | |
yield $fileItem; | |
} | |
} | |
closedir($handle); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for the code!