Files by extension
Returns all files from a given folder and filters them by a given extension
function get_files_by_ext($path, $ext){ $files = array(); if (is_dir($path)){ $handle = opendir($path); while ($file = readdir($handle)) { if ($file[0] == '.'){ continue; } if (is_file($path.$file) and preg_match('/\.'.$ext.'$/', $file)){ $files[] = $file; } } closedir($handle); sort($files); } return $files; } /* ** Example: */ print_r(get_files_by_ext('data/', 'txt')); /* returns: Array ( [0] => readme_1.txt [1] => readme_2.txt ) */
Snippet Details
-
AuthorJonas John
-
LicensePublic Domain
-
LanguagePHP
-
Created05/05/2006
-
Updated05/05/2006
-
Tagsdirectory functions, files
dir_list('data/', 'txt'); => returns all *.txt files from the data/ folder
Sorry folks, comments have been deactivated for now due to the large amount of spam.
Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!
Older comments:
Chris Buckley November 02, 2008 at 16:44
You can save yourself a lot of effort here by using the built-in glob function.