Skip to content

Instantly share code, notes, and snippets.

@g1ll

g1ll/listfolders.php

Last active Sep 15, 2019
Embed
What would you like to do?
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