Listing files from directory that have particular extensions in PHP

In this tutorial, we will see the PHP code snippet that will get and list the files from a directory with the particular extensions.

Now let’s start.

Assume that we have a directory “my_directory” and this directory contains various types of files having different extensions. From the list, we are going to take all the image type files which has PNG and JPG extensions.

Get all files from a directory and listing it using PHP

Get random word from English dictionary in PHP tutorial

Below is our PHP code that will get all the images having JPG and PNG extensions:

<?php

  $dir = 'my_directory';

  // Check if the directory exists
  if (file_exists($dir) && is_dir($dir) ) {
  	
  	  // Get the files of the directory as an array
      $scan_arr = scandir($dir);
      $files_arr = array_diff($scan_arr, array('.','..') );

      // echo "<pre>"; print_r( $files_arr ); echo "</pre>";

      // Get each files of our directory with line break
      foreach ($files_arr as $file) {
      	//Get the file path
      	$file_path = "my_directory/".$file;
      	// Get the file extension
      	$file_ext = pathinfo($file_path, PATHINFO_EXTENSION);
      	if ($file_ext=="jpg" || $file_ext=="png" || $file_ext=="JPG" || $file_ext=="PNG") {
      		echo $file."<br/>";
      	}
      	
      }
  }
  else {
  	echo "Dorectory does not exists";
  }

?>

In the above code, we have used scandir() PHP function. The scandir function of PHP is inbuilt in PHP. If we pass the directory path as the parameter in this function, it will return an array contains all the file names with extensions. Well, it also contains the parent and child directory path. Using array_diff() function we removed it.

Get random text by line number from a text file in PHP

After that, we have used foreach loop to get all the files. Before we list them we have check file extensions and if we find it has the extensions that we want then it will display the file name. We have used the pathinfo() PHP function to get the extension. Well, the extension could be both in lower case or upper case. So we have checked the extensions also for lower case.

Well, by modifying our code we can list files by checking both multiple and single file extensions.

So we did it.

 

Leave a Reply

Your email address will not be published. Required fields are marked *