Read a directory and export pretty directory list


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

This script reads a directory of files. After reading the directory specified it outputs the directory files. Upon output, supplied functions manipulate each filename and format it to make the output filename look better. e.g.: instead of output being 'my-good-looking-file.txt' it would look like 'My Good Looking File'.


Copy this code and paste it in your HTML
  1. // This script reads a directory of files. After reading the directory specified it outputs the directory files.
  2. // Upon output, supplied functions manipulate each filename and format it to make the output filename look better.
  3. // e.g.: instead of output being 'my-good-looking-file.txt' it would look like 'My Good Looking File'.
  4.  
  5. // In order for the output to look better, you must put a hyphen (-) or an underscore (_) between each
  6. // word that you want to be separated.
  7.  
  8.  
  9. // function to strip off the file extension
  10. function strip_ext($name) {
  11. $ext = strrchr($name, '.');
  12. if($ext !== false) {
  13. $name = substr($name, 0, -strlen($ext));
  14. }
  15. return $name;
  16. }
  17. // function to remove the hyphen or underscore from filename.
  18. function removeHyphen($filename) {
  19. $target = $filename;
  20. $patterns[0] = '/-/';
  21. $patterns[1] = '/_/';
  22. $replacements[0] = ' ';
  23. $replacements[1] = ' ';
  24. $filename = preg_replace($patterns, $replacements, $target);
  25. return $filename;
  26. }
  27. // function to capatalize the first character of each word. Must be called after
  28. // the removal of the hyphen or underscore
  29. function capFirstWord($word) {
  30. $cap = $word;
  31. $cap = explode(' ', $cap);
  32. foreach($cap as $key => $value) {
  33. $cap[$key] = ucfirst($cap[$key]);
  34. }
  35. $word = implode(' ', $cap);
  36. return $word;
  37. }
  38. // Formats the file. This is the main function that calls all functions explained above.
  39. function formatFile($name) {
  40. $name = strip_ext($name);
  41. $name = removeHyphen($name);
  42. $name = capFirstWord($name);
  43. return $name;
  44. }
  45. // Sets up the directory you would like to use as the "reading" directory.
  46. $mydir = dir('./dir');
  47. while(($file = $mydir->read()) !== false) {
  48. // Security - remove "." and ".." files (directories)
  49. if ($file != "." && $file != "..") {
  50. // Output. This is what is actually outputed by the script and that shows
  51. // up on the screen (browser).
  52. echo "<p><a href='./dir/$file' title='Download $file'>".formatFile($file)."</a></p>";
  53. }
  54. }
  55. $mydir->close();

URL: http://www.deckerd.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.