Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Listing all directories and sub-directories recursively in drop down menu [duplicate]

Possible Duplicate:
PHP Get all subdirectories of a given directory

I want a drop down menu to show all sub-directories in ./files/$userid/ not just the main folder. For example: /files/$userid/folder1/folder2/

My current code is:

HTML:

<select name="myDirs">
<option value=""  selected="selected">Select a folder</option>

PHP:

if (chdir("./files/" . $userid)) {

       $dirs = glob('*', GLOB_ONLYDIR);
       foreach($dirs as $val){
          echo '<option value="'.$val.'">'.$val."</option>\n";
       }        
        } else {
       echo 'Changing directory failed.';
}
like image 705
Brian Avatar asked Jan 13 '13 15:01

Brian


3 Answers

You can write your own recursive listing of the directories like:

function expandDirectories($base_dir) {
      $directories = array();
      foreach(scandir($base_dir) as $file) {
            if($file == '.' || $file == '..') continue;
            $dir = $base_dir.DIRECTORY_SEPARATOR.$file;
            if(is_dir($dir)) {
                $directories []= $dir;
                $directories = array_merge($directories, expandDirectories($dir));
            }
      }
      return $directories;
}

$directories = expandDirectories(dirname(__FILE__));
print_r($directories);
like image 77
unused Avatar answered Nov 13 '22 23:11

unused


RecursiveDirectoryIterator should do the trick. Unfortunately, the documentation is not great, so here is an example:

$root = '/etc';

$iter = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST,
    RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);

$paths = array($root);
foreach ($iter as $path => $dir) {
    if ($dir->isDir()) {
        $paths[] = $path;
    }
}

print_r($paths);

This generates the following output on my computer:

Array
(
    [0] => /etc
    [1] => /etc/rc2.d
    [2] => /etc/luarocks
    ...
    [17] => /etc/php5
    [18] => /etc/php5/apache2
    [19] => /etc/php5/apache2/conf.d
    [20] => /etc/php5/mods-available
    [21] => /etc/php5/conf.d
    [22] => /etc/php5/cli
    [23] => /etc/php5/cli/conf.d
    [24] => /etc/rc4.d
    [25] => /etc/minicom
    [26] => /etc/ufw
    [27] => /etc/ufw/applications.d
    ...
    [391] => /etc/firefox
    [392] => /etc/firefox/pref
    [393] => /etc/cron.d
)
like image 53
PleaseStand Avatar answered Nov 13 '22 22:11

PleaseStand


You can use a recursive glob implementation like in this function:

function rglob($pattern='*', $path='', $flags = 0) {
$paths=glob($path.'*', GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT);
$files=glob($path.$pattern, $flags);
foreach ($paths as $path) {
  $files=array_merge($files,rglob($pattern, $path, $flags));
}
return $files;
}
like image 3
Alex Avatar answered Nov 14 '22 00:11

Alex