Friday, 10 August 2018

Recursive Directory Listing With PHP

Use the following function to list the contents of one or more nested directories.
  1. function recursive_directory($dirname,$maxdepth=10, $depth=0){
  2. if ($depth >= $maxdepth) {
  3. return false;
  4. }
  5. $subdirectories = array();
  6. $files = array();
  7. if (is_dir($dirname) && is_readable($dirname)) {
  8. $d = dir($dirname);
  9. while (false !== ($f = $d->read())) {
  10. $file = $d->path.'/'.$f;
  11. // skip . and ..
  12. if (('.'==$f) || ('..'==$f)) {
  13. continue;
  14. };
  15. if (is_dir($dirname.'/'.$f)) {
  16. array_push($subdirectories,$dirname.'/'.$f);
  17. } else {
  18. array_push($files,$dirname.'/'.$f);
  19. };
  20. };
  21. $d->close();
  22. foreach ($subdirectories as $subdirectory) {
  23. $files = array_merge($files, recursive_directory($subdirectory, $maxdepth, $depth+1));
  24. };
  25. }
  26. return $files;
  27. }
Use this in the following way.
  1. $files = recursive_directory('folder');
  2. print_r($files); // print the result...
The maximum depth that the function will travel down is set to 10 as a default. This can be overwritten at runtime.
  1. $files = recursive_directory('folder', 20); // make maximum level 20
  2. print_r($files); // print the result...

0 comments:

Post a Comment