PHP get all files in directory with extension

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.

get all files in directory

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 '<img width="30px" src="'.$image_path.'"> ';   // echo image with tag
    }
  }
}
Still you face problems, feel free to contact with me, I will try my best to help you.