Home » Php » PHP file listing multiple file extensions

PHP file listing multiple file extensions

Posted by: admin April 23, 2020 Leave a comment

Questions:

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…

How to&Answers:
$files = glob("*.{jpg,png,gif}", GLOB_BRACE);

Answer:

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

Answer:

I just needed this for my own project. I made a converter from array to string.

function whitelistToBrace($whitelist) {
  $str = "{";
  $whitelist = !empty($whitelist) ? $whitelist : ['*'];

  foreach($whitelist as $extension) {
    $str .= '*.' . strtolower($extension) . ',';
  };

  $str = substr($str, 0, -1) . '}';

  return $str;
}

Usage

$whitelist = [
  'png',
  'jpg'
];

// glob('my/path/*.{*.png,*.jpg}', GLOB_BRACE);
$glob = glob('my/path/' . whitelistToBrace($whitelist), GLOB_BRACE);
print_r($glob);