Php get all files with extension

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 -

  • glob[]

answered Sep 30, 2012 at 19:56

LixLix

46.6k12 gold badges97 silver badges127 bronze badges

5

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.

answered Dec 16, 2011 at 23:10

mariomario

142k20 gold badges236 silver badges285 bronze badges

4

PHP's glob[] function let's you specify a pattern to search for.

answered Dec 16, 2011 at 23:02

Linus KleenLinus Kleen

32.9k11 gold badges89 silver badges99 bronze badges

0

You can try using GlobIterator

$iterator = new \GlobIterator[__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME];
$array = iterator_to_array[$iterator];
var_dump[$array];

Hassaan

6,8485 gold badges29 silver badges48 bronze badges

answered Sep 30, 2012 at 20:19

BabaBaba

92.6k28 gold badges164 silver badges215 bronze badges

glob[$pattern, $flags]


answered Sep 30, 2012 at 19:56

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

}

answered Sep 30, 2012 at 19:57

3

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

answered Sep 30, 2012 at 19:57

Not the answer you're looking for? Browse other questions tagged php filesystems or ask your own question.

  • Last Updated : 28/07/2021

Getting all files from a directory with an extension is not so hard things. In this post, we will learn how can we fetch all files from a folder in PHP.

Fetch all files or display all files in HTML tag from a folder using PHP is so easy. We just need to open the folder using PHP the "opendir[]" function and then read the directory until the end using the "readdir[]" function.
In this post, I will provide you the complete guideline to fetch or display all files from a folder to HTML using PHP. Also, I will provide you the source code so that you can understand it better.

Algorithm of getting all files from a folder using PHP

  • ✅ Open the folder using the “opendir[]” function.
  • ✅ Read the folder using the “readdir[]” function.
  • ✅ Check is it file on not.
  • ✅ Read until files end.
  • ✅ Understand the file type.
  • ✅ Ecco with HTML tag.

Open a directory using PHP

To open a folder using PHP you need to use the “opendir[]” function this function will take the location of your folder as a string and return the opened folder.

$location = "./upload";
$folder = opendir[$location];

Note: here we open the ‘upload’ folder.

Read a folder using PHP

To read a folder using PHP we need to use the "readdir[]" function. This function will take an opened folder. That means a folder that is already opened using PHP "opendir[]" function.

$files = readdir[$folder]

Note: here we open the ‘upload’ folder.

A loop through on directory until file reading end using PHP

To loop until file read end we can use while loop, and inside the while loop’s condition, we need to use file read function.

while [false != [$files = readdir[$folder]]] {
    // now echo $file variable if it is actull file
	if[$file != '.' && $file != '..']{
		// actual file path
	}
}

Note: we know in every folder there is a single and double dot has defaulted, that’s why we need to skip through using the if condition.

Note: if your directory has multiple types of files you can check the file type just getting the extension of the file from the file path.

Getting all files with extension

$str_to_arry = explode['.',$file];
$extension   = end[$str_to_arry];
if[$extension == ‘jpg’]{
	echo "it is image";
}

Getting all image from a directory and display in the website with HTML tag

$location = "./upload";
$folder = opendir[$location]; // open folder

if[$folder]{
$index = 0;
  while [false != [$image = readdir[$folder]]] { // read until end
    if[$image != '.' && $image != '..']{ // remove . and ..
        $image_path = "upload/".$image;
        echo ' ';   // echo image with tag
    }
  }
}

Still you face problems, feel free to contact with me, I will try my best to help you.

Search Post [Max:65,Min:3 Characters] Search

Search

    📖 You should learn Also 😍

        How can I get file extension in PHP?

        There are a few different ways to extract the extension from a filename with PHP, which is given below: Using pathinfo[] function: This function returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned.

        How do I get a list of files in a directory in PHP?

        The scandir[] function returns an array of files and directories of the specified directory.

        How do you find the file extension?

        Right-click the file. Select the Properties option. In the Properties window, similar to what is shown below, see the Type of file entry, which is the file type and extension.

        What is $_ files in PHP?

        PHP $_FILES The global predefined variable $_FILES is an associative array containing items uploaded via HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute set to multipart/form-data.

        Chủ Đề