Last active
February 14, 2024 12:55
-
-
Save mrwadson/5b0de63667e61f544c9ca186cce32828 to your computer and use it in GitHub Desktop.
Recursive scan directory examples
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 | |
// Recursive scan directories and collect data (use `scandir` function) | |
function scan_dir($dir) | |
{ | |
$result = []; | |
$filenames = array_diff(scandir($dir), ['.', '..']); | |
foreach ($filenames as $file) { | |
if (is_dir("$dir/$file")) { | |
array_push($result, ...scan_dir("$dir/$file")); | |
} else { | |
$result[] = "$dir/$file"; | |
} | |
} | |
return $result; | |
} | |
// print `~/Documents` directories and files | |
$user = exec('whoami'); | |
$files = scan_dir("/home/$user/Documents"); | |
print_r($files); |
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 | |
// Recursive scan directories and print type (use `glob` function) | |
function scan_recursive($dir) | |
{ | |
$tree = glob(rtrim($dir, '/') . '/*'); | |
if (is_array($tree)) { | |
foreach ($tree as $file) { | |
echo $file; | |
if (is_dir($file)) { | |
echo " -> DIRECTORY\n"; | |
scan_recursive($file); | |
} elseif (is_file($file)) { | |
echo " -> FILE\n"; | |
} | |
} | |
} | |
} | |
// print `~/Documents` directories and files | |
$user = exec('whoami'); | |
scan_dir("/home/$user/Documents"); |
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 | |
// Recursive scan directories for files with PHP iterator function | |
function scan_recursive_iterator($dir) | |
{ | |
$recursiveIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); | |
/** @var SplFileInfo $file */ | |
foreach ($recursiveIterator as $file) { | |
echo $file; | |
if ($file->isDir()) { | |
echo " -> DIRECTORY\n"; | |
} elseif ($file->isFile()) { | |
echo " -> FILE\n"; | |
} | |
} | |
} | |
// print `~/Documents` directories and files | |
$user = exec('whoami'); | |
$files = scan_recursive_iterator("/home/$user/Documents"); | |
print_r($files); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment