Home » Php » filesystems – Best way to get files from a dir filtered by certain extension in php

filesystems – Best way to get files from a dir filtered by certain extension in php

Posted by: admin April 23, 2020 Leave a comment


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.

How to&Answers:

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

glob – Find pathnames matching a pattern

Here is an example usage –

$files = array();
foreach (glob("/path/to/folder/*.txt") as $file) {
  $files[] = $file;

Reference –


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.


PHP’s glob() function let’s you specify a pattern to search for.


You can try using GlobIterator

$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);


glob($pattern, $flags)

foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";


try this

//path to directory to scan
$directory = "../file/";

//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");

//print each file name
foreach($file as $filew)
echo $filew;
$files[] = $filew; // to create the array



haven’t tested the regex but something like this:

if ($handle = opendir('/file/path')) {

    while (false !== ($entry = readdir($handle))) {
        if (preg_match('/\.txt$/', $entry)) {
            echo "$entry\n";