Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get files from a dir filtered by certain extension in php [duplicate]

Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!

So right now I have a directory and I am getting a list of files

$dir_f = "whatever/random/"; $files = scandir($dir_f); 

That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.

like image 985
CodeCrack Avatar asked Dec 16 '11 23:12

CodeCrack


2 Answers

PHP has a great function to help you capture only the files you need. Its called glob()

glob - Find pathnames matching a pattern

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Here is an example usage -

$files = glob("/path/to/folder/*.txt"); 

This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.

Reference -

  • glob()
like image 76
Lix Avatar answered Sep 20 '22 13:09

Lix


If you want more than one extension searched, then preg_grep() is an alternative for filtering:

 $files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f)); 

Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.

like image 37
mario Avatar answered Sep 22 '22 13:09

mario