Another Directory Crowler


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

Sometime it is convenient to get recursive directory listing as array of items
directory => (file array)
Such as:

Array
(
[./a2temple] => Array
(
[0] => example13.zip
)

[./rand] => Array
(
[0] => rand.zip
)

[./pstudio] => Array
(
[0] => pstudio.zip
)

[./myview/private] => Array
(
[0] => logs.zip
)

[./myview] => Array
(
[0] => myview-2.zip
)

[.] => Array
(
[0] => testutf.zip
[1] => RBAC.ZIP
)

)

My function can get optional extension filter and returns count of files found.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function fillEntries($dir, &$entries, $ext = '')
  4. {
  5. $l = strlen($ext);
  6. $d = dir($dir);
  7. $subEntries = array();
  8.  
  9. while (($entry = $d->read()) !== false)
  10. {
  11. // skip hidden files, . and ..
  12. if ($entry{0} != '.')
  13. {
  14. if (is_file($dir.'/'.$entry))
  15. {
  16. // case insensitive extension test
  17. if (!$l || strcasecmp(substr($entry, -$l), $ext) == 0)
  18. $subEntries[] = $entry;
  19. }
  20. else
  21. fillEntries($dir.'/'.$entry, $entries, $ext);
  22. }
  23. }
  24. $d->close();
  25.  
  26. if (!empty($subEntries))
  27. $entries[$dir] =& $subEntries;
  28.  
  29. // return count of "leaf" nodes
  30. return count($entries, COUNT_RECURSIVE) - count($entries);
  31. }
  32.  
  33. $entries = array();
  34. // NB: extension parameter with dot char
  35. $count = fillEntries('.', $entries, '.zip');
  36. $content = print_r($entries, TRUE);
  37. echo "There are {$count} entries:
  38. <pre>
  39. {$content}
  40. </pre>
  41. ";

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.