This is the simple example to list contents of any Directory. To do this we are going to define function DirDisply( ) which will read the current directory contents and display it as a list.
We first open current directory by $TrackDir=opendir(".");
The opendir function returns a directory handle resource on success, or FALSE on failure.
Syntax is:
opendir ( string path [, resource context] )
Where:
Path - The directory path that is to be opened
Context - For a description of the context parameter, refer to the streams section of the php manual.
Here “.” Indicates the directory which contain current php file and read each element of directory and display it using a while loop.
while ($file = readdir($TrackDir)) {
if ($file == "." || $file == "..") { }
else {
print "<tr><td><font face=\"Verdana, Arial, Helvetica, sans-serif\"><a href=$file target=_blank>$file</a></font> </td>";
print "<td> ".filetype($file)."</td></tr><br>";
}
}
And then we have to close directory by closedir($TrackDir); Which Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().
Syntx:
void closedir ( resource dir_handle )
Where,
dir_handle - The directory handle resource previously opened with opendir().
When I run complete script on Web server I got result as below shown in figure:

Our complete piece of code will be as listing below:
<?php
/*
function that reads directory content and
returns the result as links to every file in the directory
also it disply type wheather its a file or directory
*/
function DirDisply() {
$TrackDir=opendir(".");
while ($file = readdir($TrackDir)) {
if ($file == "." || $file == "..") { }
else {
print "<tr><td><font face=\"Verdana, Arial, Helvetica, sans-serif\"><a href=$file target=_blank>$file</a></font> </td>";
print "<td> ".filetype($file)."</td></tr><br>";
}
}
closedir($TrackDir);
return;
}
?> <b><font face="Verdana, Arial, Helvetica, sans-serif">Current Directory Contain
Following files and Sub Directories...</font></b>
<p>
<?php
@ DirDisply();
?>
Download
Download source code for 'Directory Listings, list files and subfolder using php'
Download















