PHP file listing multiple file extensions

Here is my current code:

$files = glob("*.jpg");

This works fine. However, I am wanting to list other image types, such as .png, gif etc.

Can I please have some help to modify this above code to get it working. I have tried the following with no success:

$files = glob("*.jpg","*.png","*.gif");

$files = glob("*.jpg,*.png,*.gif);

And other variations...


$files = glob("*.{jpg,png,gif}", GLOB_BRACE);

My two cents:

$availableImageFormats = [
"png",
"jpg",
"jpeg",
"gif"];
$searchDir = /*yourDir*/;
$imageExtensions = "{";
foreach ($availableImageFormats as $extension) {
    $extensionChars = str_split($extension);
    $rgxPartial = null;
    foreach ($extensionChars as $char) {
        $rgxPartial .= "[".strtoupper($char).strtolower($char)."]";
    }
    $rgxPartial .= ",";
    $imageExtensions .= $rgxPartial;
};
$imageExtensions .= "}";
glob($searchDir."/*.".$imageExtensions, GLOB_BRACE)

With this you can create an array of all the extensions you are looking for without worrying of improper case use. Hope it helps


05 2021

This is just an expansion of @Jeroen answer.

Somethings to keep in mind

'flag' is Important

Since you are using curly brackets, keep in mind GLOB_BRACE required. Without the flag you will get a empty array if items

$files = glob("*.{jpg,png,gif}", GLOB_BRACE);

Sorting

This will also help you to sort the files in the way you have written.

$files = glob("*.{jpg,png,gif}", GLOB_BRACE);
xx.jpg
xx.jpg
xx.png
xx.gif
xx.gif

$files = glob("*.{gif,jpg,png}", GLOB_BRACE);
xx.gif
xx.gif
xx.jpg
xx.jpg
xx.png

+ Bonus

If you have to list out all the files but without folder, you can use this

$files = glob("*.{*}", GLOB_BRACE);