Skip to content

Instantly share code, notes, and snippets.

@g1ll
Last active September 15, 2019 18:47
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 g1ll/5a0879f5d48440633012381d3157c687 to your computer and use it in GitHub Desktop.
Save g1ll/5a0879f5d48440633012381d3157c687 to your computer and use it in GitHub Desktop.
Recursive PHP function to list folders and subforlders of a directory and returned a PHP Array.
<?php
function getFolders($dir = false) {
$server_sign = filter_input(INPUT_SERVER, 'SERVER_SIGNATURE', FILTER_SANITIZE_STRING);
$unix_server = (stristr($server_sign, "win")) ? false : true;
$slash = ($unix_server) ? "/" : "\\";
$dir = (!$dir) ? getcwd() : $dir;
$open_dir = opendir($dir);
$folders = [];
while ($item = readdir($open_dir)) {
if ($item != "." && $item != "..") {
$path = filetype(realpath($dir . $slash . $item));
if ($path == "dir") {
$folders[] = $item;
foreach (getFolders(realpath($dir . $slash . $item)) as $folder) {
$folders[] = $item . $slash . $folder;
}
}
}
}
return $folders;
}
//TEST
echo "<pre>";
print_r(getFolders());
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment