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 -

  • 75
Reply Report

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.

  • 15
Reply Report
    • This answer was extremely helpful for me! I was trying to search for hundreds of different file identifiers and files in a folder with tens to hundreds of thousands of files. glob couldn't handle such a big search string, and if I broke into into smaller strings and looped it took several minutes. using preg_grep with scandir takes about 5 seconds!
    • Thanks for introducing preg_grep to me. This is much more helpful as compared to glob it can handle case insensitives.

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

  • 2
Reply Report

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

  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions