John Beasley
John Beasley

Reputation: 3073

PHP show specific directory files

Trying to only show specific files to my page. I'm returning a thumbs.db file, which is invisible in the directory. I need to only show pdf, docx, or xls files.

 <?php
   function returnEmpdisDocs()
   {
     $dir = "empdis/docs/";
     $ffs = scandir($dir);

     foreach($ffs as $ff)
     {
       if($ff != '.' && $ff != '..')
       {
         $filesize = filesize($dir . '/' . $ff);    
         echo "<li><a download href='$dir/$ff'>$ff</a></li>";
       }
     }
   }
   returnEmpdisDocs();
 ?>

My question is: what can I add to the above code to only include pdf, docx, and xls files?

Upvotes: 0

Views: 97

Answers (1)

JOUM
JOUM

Reputation: 239

Just replace this:

if($ff != '.' && $ff != '..')

and use that:

if($ff != '.' && $ff != '..' && preg_match('#\.(pdf|docx|xls)$#',$ff))

the regex \.(pdf|docx|xls)$ tests that a string ends with one of the given words

little update: better test for real extentions (noted by Patrick), i added \.

Upvotes: 1

Related Questions