47

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.

Community
  • 1
  • 1
CodeCrack
  • 5,253
  • 11
  • 44
  • 72

7 Answers7

112

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 -

Lix
  • 47,311
  • 12
  • 103
  • 131
  • 4
    please do not answer obvious duplicates but closevote them. thanks. – Gordon Sep 30 '12 at 19:57
  • 5
    @gor - needed more than just my vote to close as a [dupe](http://stackoverflow.com/questions/1646099/scan-current-folder-using-php)... – Lix Sep 30 '12 at 20:00
  • 1
    @Lix why not to use `$files = glob("/path/to/folder/*.txt")` directly without `for` ?. I think it's the same – Mohamad Osama Jun 24 '20 at 10:02
  • @MohamadOsama - You're absolutely right :) Always fun to look back 8 years at my old code haha! Thanks for the feedback! – Lix Jun 25 '20 at 06:37
  • 2
    @Lix - Yes it's very old code but these help me fix my problem nowadays. you are welcome Bro. – Mohamad Osama Jun 26 '20 at 09:36
21

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.

mario
  • 144,265
  • 20
  • 237
  • 291
  • 6
    `glob("{$dir}*.{jpg,jpeg,gif,ico,png}", GLOB_BRACE)`. This would work as well for multiple extensions. – Savas Vedova Oct 08 '13 at 06:14
  • 1
    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! – William W Feb 25 '15 at 21:11
  • Thanks for introducing preg_grep to me. This is much more helpful as compared to glob it can handle case insensitives. – Juergen Schulze May 11 '19 at 13:15
  • This works with square brackets in the path, while square brackets using glob() have to be escaped. – Dmytro Dzyubak Oct 14 '20 at 00:56
9

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

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
6

You can try using GlobIterator

$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);
Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Baba
  • 94,024
  • 28
  • 166
  • 217
2

glob($pattern, $flags)

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>
Christopher Tarquini
  • 11,176
  • 16
  • 55
  • 73
2

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

}
Database_Query
  • 626
  • 4
  • 14
2

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

    closedir($handle);
}
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153