Recursive Glob File Tree


/ Published in: PHP
Save to your folder(s)

There are a lot of recursive glob functions out there but they don't build a tree, they build a 1 dimensional array...This function builds a directory tree.


Copy this code and paste it in your HTML
  1. /* to use:
  2. pattern = glob pattern to match
  3. flags = glob flags
  4. path = path to search
  5. depth = how deep to travel, -1 for unlimited, 0 for only current directory
  6. */
  7.  
  8. $folders = folder_tree('*.*', 0, '/path_here/', -1);
  9.  
  10. print_r($folders);
  11.  
  12. function folder_tree($pattern = '*', $flags = 0, $path = false, $depth = 0, $level = 0) {
  13. $tree = array();
  14.  
  15. $files = glob($path.$pattern, $flags);
  16. $paths = glob($path.'*', GLOB_ONLYDIR|GLOB_NOSORT);
  17.  
  18. if (!empty($paths) && ($level < $depth || $depth == -1)) {
  19. $level++;
  20. foreach ($paths as $sub_path) {
  21. $tree[$sub_path] = folder_tree($pattern, $flags, $sub_path.DIRECTORY_SEPARATOR, $depth, $level);
  22. }
  23. }
  24.  
  25. $tree = array_merge($tree, $files);
  26.  
  27. return $tree;
  28. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.