List Contents of a Directory


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

To make an image browser, add these lines:

$ext = strtolower(substr("$dirArray[$index]", strrpos("$dirArray[$index]", '.') + 1)); //get file extensions

if ("$ext" == "jpg") { // if file is a jpg

print("$dirArray[$index]<a href=\"$dirArray[$index]\"></a>"); // show image and create link to it


Copy this code and paste it in your HTML
  1. // open this directory
  2. $myDirectory = opendir(".");
  3.  
  4. // get each entry
  5. while($entryName = readdir($myDirectory)) {
  6. $dirArray[] = $entryName;
  7. }
  8.  
  9. // close directory
  10. closedir($myDirectory);
  11.  
  12. // count elements in array
  13. $indexCount = count($dirArray);
  14. Print ("$indexCount files<br>\n");
  15.  
  16. // sort 'em
  17. sort($dirArray);
  18.  
  19. // print 'em
  20. print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
  21. print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");
  22. // loop through the array of files and print them all
  23. for($index=0; $index < $indexCount; $index++) {
  24. if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
  25. print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
  26. print("<td>");
  27. print(filetype($dirArray[$index]));
  28. print("</td>");
  29. print("<td>");
  30. print(filesize($dirArray[$index]));
  31. print("</td>");
  32. print("</TR>\n");
  33. }
  34. }
  35. print("</TABLE>\n");

URL: http://www.liamdelahunty.com/tips/php_list_a_directory.php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.