How to Display Directory Content Using PHP

How to display directory content using php - By using PHP we can open, display the contents and close a directory. PHP provides the function of opendir() to open the directory, readdir() to display the contents of the directory and closedir() to close the directory.To display the contents of the directory, all three functions must be used simultaneously.
To better understand it, here I give examples of its application to a program.
Program
File Name: file09.php
Description: Program displays files and directories in a directory.
Type the following php code into notepad.
<?php
$dir = "images";
if ($handle = opendir($dir)) {
 while (false !== ($file = readdir($handle))) {
  if ($file != "." && $file != "..") {
   echo "$file<br>";
  }
 }
closedir($handle);
}
?>


Save the php code with the name: file09.php in the htdocs folder
Program Explanation
The above program will display on screen, all files and directories that are in the "images" directory. The function of opendir() on line 3 is to open the directory. While the readdir() function will read the files in the directory one by one in sequence. The closedir() function on line 9 is to close the opening of the directory.
To run the program, open the browser then type http://localhost/file09.php in the address bar then enter. Then the result will look like this.
The program does not display anything if in that directory there is no file or folder. Consider the following picture.
How to Display Directory Content Using PHP
The program does not display anything

How to Display Directory Content Using PHP
No files or folders in the images directory

The program displays the contents of the directory because in the directory there is a file or folder.
How to Display Directory Content Using PHP
The program displays the contents of the directory

How to Display Directory Content Using PHP
In the images directory there are files or folders

That is a tutorial that I can give about how to display directory content using php. Hopefully the tutorial can improve our ability in understanding the php programming language. See also tutorial: How to Create Directory Using PHP.

Comments

  1. eliteonrent
    we provide online rental services for air conditioner & oil heater
    for more information contact us

    ReplyDelete

Post a Comment