John Beasley John Beasley - 11 months ago 88
PHP Question

PHP show specific directory files

Code World, people.

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

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>";

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

Your assistance is greatly appreciated. Thank you in advance.

Answer Source

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 \.