Posted By

noelj on 12/26/10


Tagged

dir files


Versions (?)

Scan directory contents recursively


 / Published in: PHP
 

  1. <?php
  2. function dir_recursive($path, $parent = ''){
  3. $files = array();
  4.  
  5. $d = dir($path);
  6. while (false !== ($entry = $d->read())) {
  7. if($entry == '.' || $entry == '..')
  8. continue;
  9.  
  10. //if this is a directory, loop inside its contents
  11. if(is_dir($d->path.'/'.$entry)){
  12. //if parent dir given, then create another array dimension to be used to store files under this parent
  13. if(!empty($parent)){
  14. $files[$parent][$entry] = dir_recursive($d->path.'/'.$entry, $entry);
  15. }else
  16. $files[$entry] = dir_recursive($d->path.'/'.$entry, $entry);
  17. }else
  18. $files[$entry] = $entry;
  19.  
  20. //reset parent dir given, so it won't create another array dimension for the next loop of subdirectory
  21. $parent = '';
  22. }
  23. $d->close();
  24.  
  25. return $files;
  26. }
  27.  
  28. //usage
  29. $files = dir_recursive('.');
  30. echo '<pre>'; print_r($files);
  31.  
  32. ?>

Report this snippet  

You need to login to post a comment.