Scan folder for file extension

Started on the old forum in April 2011 · view the original in the archive · old links redirect here

No replies · 1,472 views · started 15 years ago · 1 min read

arnage Lead · 811 posts #1

Scan specified folder for files by specified extension.

function list_files_ext($folder, $ext) {
$files = array();
if (is_dir($folder)) {
$handle = @opendir($folder);
while ($file = readdir($handle)) {
if ($file == '.' || $file == '..') { continue; }
if (is_file($folder.$file) && preg_match('/^[a-z0-9-_\.]+\.(['.$ext.']{2,4})$/iD', $file)) {
$files[] = $file;
}
}
closedir($handle);
if (!sort($files)) { exit; }
}
return $files;
}

Usage:

$list = list_files_ext('images/', 'jpg');
for ($i=0; $i<count($list); $i++) {
echo '
'.$list[$i].'<br/>';
}

It lists files like: image.jpg back.jpg tool.jpg ...

Or something like:

function list_files_ext($folder, $ext) {
$files = array();
if (is_dir($folder)) {
$handle = @opendir($folder);
while ($file = readdir($handle)) {
if ($file == '.' || $file == '..') { continue; }
if (is_file($folder.$file) && preg_match('/^[a-z0-9-_\.]+\.(['.$ext.']{2,4})$/iD', $file)) {
$files[] = $file;
}
}
closedir($handle);
if (!sort($files)) { exit; }
}
foreach ($files as $list) {
echo '
<a href="./'.$folder.$list.'">'.$list.'</a><br/>';
}
return;
}
list_files_ext('images/', 'jpg');
<!DOCTYPE html PUBLIC "-//***WAPFORUM**.**RS***

Write your reply now; next you create a free account (or sign in) and it is posted right away. Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close