How to create a php file to show list of files in directory ?

H

PHP Code SnippetI have come across a situation where I need to place some softwares in a particular folder in my host but at the same time I want to provide my visitors to see what all available softwares are available in that particular folder. By default Apache provides list of files in a directory but in some cases it do not. It is easier to write the simple piece of php code to display list of files in a directory with a link to that file so that the user can download the file by just clicking and adding for that we can customize using CSS to display stylizing it.

Just place the following piece of code in a file and save it as “index.php” and transfer it into the directory for which you need to create directory

[php]

<?php
if ($handle = opendir(‘.’)) {
$kb = 1024;
$dirlist .= ‘<table border=0><tr><th>File Name</th><th>File Size</th></tr>’;
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != "index.php")
{
$dirlist .= ‘<tr><td><a href="’.$file.’">’.$file.'</a></td>’;
$sizeinbits = filesize($file);
$sizeinkb = $sizeinbits / $kb;
$dirlist .= ‘<td>’.$sizeinkb.’ Kb</td></tr>’;
}
}
closedir($handle);
$dirlist .= ‘</table>’;
}
?>
<P>List of files:</p>
<P><?php echo $dirlist ?></p>[/php]

Once you place this index.php file by default this page opens up and shows the list of files in that particular and in addition to this you can customize the way it can be displayed by styling it using CSS.

Hope this helps you and feel free to comment if you have any queries.

About the author

pavankumar.p1990
By pavankumar.p1990