Archive

Posts Tagged ‘list files in a directory’

List files in a directory using php

September 13th, 2009 1 comment

To display a list of files within a directory using PHP you need to use opendir() and readdir(). Below is a function that will return the list of files and remove the . and .. from the listing.

  1.  
  2. //full path of directory
  3. $dir = "/var/www/images/";
  4.  
  5. function listFiles($dir){
  6.  
  7. //open directory and read its contents
  8. if ($handle = opendir($dir)) {
  9. while (false !== ($file = readdir($handle))) {
  10.  
  11. //only display filenames
  12. if ($file != "." && $file != "..") {
  13. echo "$file\n";
  14. }
  15. }
  16. closedir($handle);
  17. }
  18. }
  19.  

You might run into trouble trying to find the correct full path of the images. For example in a windows hosting environment the path could beĀ  (c://blah/blah), in a Linux environment it could be (/var/www/blah/blah).

To find the exact path for your environment use phpinfo(). Once you have the php info look for the DOCUMENT_ROOT entry.

SEO Powered by Platinum SEO from Techblissonline