Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file listing multiple file extensions

Tags:

php

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...

like image 401
user1383147 Avatar asked May 14 '12 21:05

user1383147


People also ask

How can I get multiple file extensions in PHP?

$files = array_filter(glob('path/*. *'), function ($filename) { return preg_match('/\. (jpe? g|png|gif)$/i', $filename); }); sort($files);

Can a file have multiple extensions?

A file name may have no extensions. Sometimes it is said to have more than one extension, although terminology varies in this regard, and most authors define extension in a way that doesn't allow more than one in the same file name. More than one extension usually represents nested transformations, such as files. tar.

What are PHP file extensions?

php file extension refers to the name of a file with a PHP script or source code that has a ". PHP" extension at the end of it. It's similar to a Word file with a . doc file extension.


Video Answer


2 Answers

$files = glob("*.{jpg,png,gif}", GLOB_BRACE); 
like image 161
Jeroen Avatar answered Nov 02 '22 19:11

Jeroen


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.
The sorting below is based on the order of extensions inside the curly bracket.

$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);
like image 20
Dexter Avatar answered Nov 02 '22 17:11

Dexter