Get all files from a directory and listing it using PHP

By Faruque Ahamed Mollick

In this tutorial, we are going to get all the files from a particular directory and create the list that contains the file names of that directory.

Now we are going to write our PHP code step by step.

At first, we are going to take the directory name in a variable and then check if the directory exists or not:

$dir = 'my_directory';

// Check if the directory exists
if (file_exists($dir) && is_dir($dir) ) {
	// Our code will be here to get and list all the files from the directory
 }
 else
 {
    echo "Directory does not exist";
 }

Then we will use the PHP scandir() function to get the files inside the directory as an array. The array will contain all the files. Below is the code:

$scan_arr = scandir($dir);

The array also contains the current category and parent category indicator with “.” and “..”.

Now remove the current directory and parent directory indicator with the PHP array_diff function:

$files_arr = array_diff($scan_arr, array('.','..') );

After that, we will get an array that contains only the files from the directory.

Now we are going to use foreach loop to get each file and list it with the line break:

// Get each files of our directory with line break
foreach ($files_arr as $file) {
	//Display all our files
	echo $file."<br/>";
}

Get random word from English dictionary in PHP tutorial

Complete and final PHP code for listing all files from directory

Now below is our complete code which will get all files and list it with line break on our web page:

<?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) {
      	//Display all our files
      	echo $file."<br/>";
      }

  }
  else {
  	echo "Directory does not exist";
  }


?>

The above code will display all the files from “my_directory” line by line on our web page. Also, if the directory doesn’t exist then it will show us a message:

Directory does not exist

Set a seasonal image in PHP that will change with season

Force Download A File From Server In PHP

Leave a Reply

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