Read Folder, List Files and Link Those Files in PHP

by Hiroshi on January 12, 2013

in File Manipulation

If you want to list all files from a folder automatically by using a PHP script and get them with link then here is a very simple method to do that. This script reads contents of a folder and lists those contents with link to them.

In my case I had SQL database files to list. If you have got images to list or mp3 to list then find .sql in the following script and replace that with .jpg or .mp3 or html. This is just to replace file extension from listed item by using str_replace. Anyways give it a try. Change folder named as backups from this script according to your need.

<?php
$dir="backups";
if (is_dir($dir)) {
$fd = @opendir($dir);
while (($part = @readdir($fd)) == true) {
if ($part != "." && $part != "..") {
$file_array[]=$part;
}
}
if ($fd == true) {
closedir($fd);
}
}
sort($file_array);
reset($file_array);
for($i=0;$i<count($file_array);$i++) {
$npart=$file_array[$i];
if (strstr($npart,".sql")) {
$name=str_replace(".sql","",$npart);
print("<a href=\"$npart\">$name</a>");
print("<br>");
}
}
?>

Related Posts

Previous post:

Next post: