PHP: List Files In A Directory

August 11, 2009
By

Like I have said. This site is a little about everything. It is also a place for me to keep examples of scripts that I use from time to time in case I loose them. Misplacing items is a very common things for me, just ask my wife.

Anyway, whenever possible I will give credit to whoever or where ever I found the code. In this case I have been holding onto the code for awhile and really have no idea where I got it. So if it’s yours, speak up!

$file";
         }
      }
   }

   // ALWAYS remember to close what you opened
   closedir($handle);
}

?>

In order just to get this going all you have to do is add the directory that you want listed out right at the top where it says “dirPath”.

The next step is simple formating of how you want it displayed. Put the print out in div tags, spans or have them printed out in links. It’s all just HTML formating.

You can achieve this in 2 places. This is broke down so that it will list directories (folders) and files differently. Right below where it says “found a directory, do something with it?” is where you would put the formating for a folder and right below “found an ordinary file” is where you would out the formating for files.

The only thing required in each of these sections is the variable. The [] around the file name for folders is not necessary but is a nice way to distinguish between files and folders.

Using this above, here is a print out of my directory that is listed.
gitrdone.html
mine.txt
[folder1]
test1.php
[folder2]
your.php

Possible users? Well for me I was taking a stab at building my own blogging system similar to WordPress. It was a fun little project but I have not worked on it in a while. But in one part I have a theme editor so like WordPress and others I needed/wanted a theme editor. So this listed out the files of my current theme. I then had links (like WordPress) when clicked would open the file in a text area so that I could edit it.

Other uses include a lits of pictures in a directory. I have another little script tucked away so for listing ONLY pictures in a directory. Actually if I remember right you just determine the file types you want listed. I will have to get that one posted as well. Anyway, list them out with a link so so that people can click on the photo link and view the picture.

Or I have been putting some help files together for some co-workers. I could put the files one of my web pages and then have them listed out and of course linked. So they could click on the filename and download it.

Just suggestions.

Leave a Reply

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

*