Code Snippet
Display Styled Directory Contents
Read the current directory of files and displays a styled table of their name, file type, and file size. Icons for the different major file types (audio, doc, html, image, pdf, psd, and video).
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Display Directory Contents</title>
<style>
*{
padding:0;
margin:0;
}
html,body {
color:#333;
font-family: "Lucida Console", Courier, monospace;
font-size:14px;
text-shadow:1px 1px 1px #cacaca;
-webkit-text-shadow:1px 1px 1px #cacaca;
-moz-text-shadow:1px 1px 1px #cacaca;
}
a{
padding: 2px 0 0 24px;
color:#FE4902;
text-decoration:none;
}
a:hover{
color:#000;
}
#container{
margin:0 auto;
width:700px;
margin-top:20px;
padding-top:10px;
border:1px solid #EEE;
border-radius:10px;
-moz-border-radius:10px;
}
.head{
background-color:#FE4902;
color:#FFF;
font-weight:bold;
padding:7px 0 5px 10px;
font-size:14px;
letter-spacing:1px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.head:hover{background-color:#FE4902;}
.head span{font-size:9px; letter-spacing:0;}
td{
background-color:#F3F3F3;
padding:6px;
}
td:hover{background-color:#EFEFEF;}
h1{
font-size:18px;
font-weight:bold;
padding:0 0 10px 10px;
}
/*icons for file types (add more to suit your needs - icons by famfamfam.)*/
/*images*/
a[href$=".jpg"] {background: url(image.gif) no-repeat left 50%;}
a[href$=".gif"] {background: url(image.gif) no-repeat left 50%;}
a[href$=".png"] {background: url(image.gif) no-repeat left 0%;}
/*pdfs*/
a[href$=".pdf"] {background: url(pdf.gif) no-repeat left 50%;}
/*psds*/
a[href$=".psd"] {background: url(psd.gif) no-repeat left 50%;}
/*docs*/
a[href$=".doc"] {background: url(doc.gif) no-repeat left 50%;}
a[href$=".txt"] {background: url(doc.gif) no-repeat left 50%;}
/*videos*/
a[href$=".avi"] {background: url(video.gif) no-repeat left 50%;}
a[href$=".m4a"] {background: url(video.gif) no-repeat left 50%;}
a[href$=".mov"] {background: url(video.gif) no-repeat left 50%;}
a[href$=".mp4"] {background: url(video.gif) no-repeat left 50%;}
a[href$=".wmv"] {background: url(video.gif) no-repeat left 50%;}
/*audio*/
a[href$=".mp3"] {background: url(audio.gif) no-repeat left 50%;}
a[href$=".wma"] {background: url(audio.gif) no-repeat left 50%;}
a[href$=".aac"] {background: url(audio.gif) no-repeat left 50%;}
/*web pages*/
a[href$=".html"] {background: url(html.gif) no-repeat left 50%;}
a[href$=".php"] {background: url(html.gif) no-repeat left 50%;}
</style>
</head>
<body>
<div id="container">
<?php
// opens this directory
$myDirectory = opendir(".");
// gets each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// finds extention of file
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
// closes directory
closedir($myDirectory);
// counts elements in array
$indexCount = count($dirArray);
// sorts files
sort($dirArray);
// print 'em
print("<h1>Directory Contents</h1>");
print("<table width='100%' cellspacing='10'>
<tr>
<td class='head'>Filename</td>
<td class='head'>Type</td>
<td class='head'>Size <span>(bytes)</span></td></tr>\n");
// loops through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
print("<tr><td><a href='$dirArray[$index]'>$dirArray[$index]</a></td>");
print("<td>");
print(findexts($dirArray[$index]));
print("</td>");
print("<td>");
print(filesize($dirArray[$index]));
print("</td>");
print("</tr>\n");
}
}
print("</table>\n");
?>
</div>
</body>
</html>

Thanks to Andrew Champ.
You need to change line 136 to this to avoid a Parse error.
a href='$dirArray[$index]'After that this works perfect! Thanks for sharing!
//T
There were \” marks in there to make sure that wasn’t a problem but for whatever reason weren’t showing up in the displayed code. I just made them single ticks to avoid problems, thanks!
Very nice script, thanks for sharing!
nice script. I’m sure I can find something to use this for :)
Looks really cool – I’ll definitely be using this for something or other.
sweet. and so simple. thanks!
Nice. Thanks.
line 141:
print(number_format((filesize($dirArray[$index])), 0, ”, ‘,’));
Nice!
One thing though: where can I find the little icons on the left of the file/folder please?
Here are the icons I used, they’re great for everything!
http://www.famfamfam.com/lab/icons/
Thanks for this. This is a great bit of code and very easy to add even for a php newb like me.
I’m getting an error from this line:
print(filesize($dirArray[$index]));I think it’s line 141 in the original, but I am just using the php part as an include with my own CSS so it’s line 48 in mine. Here is the error:
Warning: filesize() [function.filesize]: stat failed for archives in /..(path to my website).org/includes/directory_contents.php on line 48I believe the error is because it is printing out the parent directory folder (and its parent, too), which have no filesize. It works great, except for those two lines – and I can’t figure out why they even are being printed, since they are not files IN the directory… My folder structure is
/newsletters/archives/index.phpand the first row of the table displaying the files shows “archives,” with the error under the filesize column, and the last row of the table shows “newsletters” and another filesize error.I’m just learning PHP, but I think a line to set the condition if there is no suffix, don’t include it might be fairly easy… for someone who is more fluent in PHP, anyway :)
Anyone have any ideas? Thanks!
I’m trying to figure it out, but realized that setting a condition for not printing a file without a “.” in the string won’t work, because the “files” that are causing the errors don’t actually exist – it’s showing the parent and “grandparent” directories as if they were files IN the directory – /newsletters/archives/archives and /newsletters/archives/newsletters
I can’t figure out what is causing that, and since they don’t actually exist in the directory, my idea for setting a condition of not printing a string without a “.” in it won’t have any effect. And it hasn’t.
Here’s the page:
http://bristleconecnps.org/newsletters/archives/index.php
I got it to stop displaying the empty line at the top and the first error – the archives one, by changing the loop to this:
for($index=4; $index < $indexCount; $index++) {starting at “1″ instead of 0 got rid of the blank, and starting at “4″ takes into consideration the two parent directories which aren’t being shown plus the weird error one, and starts on the first real file. There is still the error at the end (last row) of the table.
Okay, my head hurts, and I hope some of you wonderful PHP people and problem solvers have some better ideas!
Thanks.
I just fixed it:
for($index=4; $index < $indexCount-1; $index++) {(added -1 to the index count so it wouldn’t show the last “file”)
This is obviously a workaround that is specific to that file structure – if the directory was at a different level it would need to start at a different place, which makes using this code as an include for any directory index file I want on my site not as simple, but hey, it works!
Sorry for all the multiple comment posts, but I hope it may be helpful and/or interesting to someone! :)
And if someone has a better idea that will fix it instead of hiding it, I would love to hear it.
Thanks!!
This will prevent the last file from being listed in the directory. Do you have any idea on how to prevent the index.php from showing?
Put this line in your .htaccess file:
Then rename the file to .index.php (with the leading dot). The php script script will then prevent the showing of hidden files. The result: your index.php will not show up in the listings.
Very cool. Thank you very much Chris. I know I’m late in the game here but I’m definitely gonna use your script.
OK… I’ve played with this and it works great. Really excited about this but I don’t know enough to start adding stuff to the code. But what about adding a download function to the directory? Each of the items would get their own download button. Just an idea in case someone would like to try it. Thanks again for the script!
Hey this is great code works so sweet!
But I need to open up a different dir to where the script is located how do i do that?
Cannot get this to work. It only displays the headers on my page… no file listings, and there are plenty of files in the directory.
Any thoughts?
Dear all :
You can choose a certain file only , for example if you want to display “.doc” only without any files maybe exist in that folder, so then you should REPLACE this code instead of gets each entry to be seems as follow:
// gets each entry
while($entryName = readdir($myDirectory)) {
if (strpos($entryName, ‘.doc’,1) ) {
$dirArray[] = $entryName;
}
}
Zeyad
Anyone know how to get it to NOT display certain given files such as the favicon or the index.php file?
Better still for me: how do i make display ONLY the folder names?
Useful script. Thanks.
David
Hi David,
I had a closer look at this script, very useful indeed… my suggestion for you are:
Define (just before the while-loop): $forbiddenExts = array(“php”, “ico”, “html”);
In the while-loop, do the same as in findexts():
And if you want to display only folders, then add another line of code just before the first if:
Altogether:
!is_file()… you don’t want to display files… in my script I don’t want to display folders… ;-)
great script, but i can’t figure out how i can change the folder.
every time i change the directory there will appear a mistake in that in in which sort($dirArray); located.
what i’m supposed to do?
just another method i have used before, which displays the contents of a folder, and gives a link and preview… if anybody wants the code, let me know. example is http://www.inktecbots.com/specials.php
Hello, I like the look of your example, can you please let me have the code
hi..
i m just learning to use php… this code is gr8…
i m getting the parse error… so what is the change in line 136?
thanx
hey, im getting this to work really well, but what if i wanted to display folders and files, but excluding the php and icon files? what would i need to change?
look at @Benjamin’s post above yours!
right…but in some instances i want it to display both files AND folder, but NOT the *.ico and *.php files
Life. Saver.
I have customized the script to create a simple with links from given folders. You don’t know how this helped me out, thanks a lot.
Thanks buddy! helped me a lot
if one chances the line $myDirectory line to:
$myDirectory = opendir(“c:\docs”);
The files in the docs directory are listed correctly, however, when one clicks on the link the link ties to load the file from the localhost directory.
Is there an easy way of linking to the the files in the c:\docs directory?
Thanks
Thanks for this piece of code. Cute one
Im learner for php. This code show some error. the extenson of this file is .php rite?
excatly wht my requirement is to dispaly the file in particular local folder in webpage…. so tht clicking on the links the file shuld get downloaded….. pls can anyone help me in doin this?. i need in html
Just as a heads up, split() is deprecated in php5.3 so you will want to modify like so:
$exts = explode("[/\\.]", $filename) ;
It worked for me. Thank you very much for share!
This is not working for me. I used it as it is in php 5 but i is not working at all. what should I modify?
I’m having an issue displaying the file size when I change the directory.
http://infasyssolutions.com/control.php
Above is what I’m trying to make work. If i leave it to the (“.”) everything works perfect, but when I change it to (“images”) everything but the file size works. Any ideas as to why?
Hai.. this code helps me alot..
but i need to listout folders in the directory and also if there is any documents in that folder that also should be listout..please help me
I found a fix the issue with changing the directory.
The problem was that changing the directory prevented the hyperlink to the file from working, along with preventing the PHP processor from accessing the file to read its size. Even though it still listed the files in the folder as intended.
Do the following:
————————————————————————–
*Replace the lines:
with the lines:
————————————————————————–
Also replace:
with
You may need to use if you version of PHP is 5.3 or later.
————————————————————————–
Replace:
with:
————————————————————————–
and replace:
with
We would like to thank you for the great script you have made. Specially the thing with transperent effeect. It’s one of the coolest thing on earth.
Is there any way to load a directory from an external domain?
Not without FTP access.
Great piece of work which no doubt will help many people.
I also found the reworking of the script to show the contents of a different folder/location to be very helpful as it overcomes the problems of showing certain file types which you may not otherwise wish to make viewable.
I did however find one small issue after the rework in as much as the icons for the file types weren’t displaying in the directory listing … and in my case, having put the icons in a folder called ‘img’ I simply had to change the following lines 60 through to 89 …
I’ll only give one example to save space :
71 /*docs*/
72 a[href$=".doc"] {background: url(img/doc.gif) no-repeat left 50%;}
73 a[href$=".txt"] {background: url(img/doc.gif) no-repeat left 50%;}
74 a[href$=".rtf"] {background: url(img/doc.gif) no-repeat left 50%;}
I hope this helps … even just one person …
Anyway … MAGNIFICENT script … MANY THANKS ;-)
To get filesize of a file from another directory :
$dirname = "./YourFolderName" //Change "YourFolderName" to your folder's name
$filez = $dirArray[$index]; //Get the name of file
$path = $dir.'/'.$filen; //Path address of the file (included the directory path)
$size = filesize($path); //Get the size of a file
print("$size"); //print the size
I use PHP 5.2.10, it works fine .
HI, very nice script – thanks a lot.
I have created a page that shows the latest pdf on my web using google docs viewer.
Could the code be added to the script, so that a “view online” link is added to the file list?
The code I´m using is as follows:
” iframe src=”http://docs.google.com/gview?url=http://www.benitezjones.com/uploads/ultima.pdf&embedded=true” style=”width:718px; height:700px;” frameborder=”0″
Any ideas?
How to display the last modified date?
Add this line inside the while loop:
And then this wherever you want to output that time (still must be inside the loop):
How do you also create a css archive by adding thumbnail using first image and excerpt of a file.
Dear All;
thanks Jesus
if body can help that question
How to display the last modified date
————————————————–
Question to Help :
How to display results in limit for 30 results per page – infact this to large reults inside same folder
any help
please
Thanks a lot. Looking everywhere for one of these that worked, this code is perfect. Appreciate your addition to hide specific file types as well. Exactly what I needed.
How to display results in limit for 30 results per page – infact this to large reults inside same folder
any help
please
Is there a way to mark the directories in that directory as such.I use words ,letters and it would be helpful if they were marked somehow.This is the best Script of this type I have found.I have looked high and low for this and came across this purely by accident.Thanks Andrew for posting this for others to use
Dear all :
You can choose a certain file only , for example if you want to display “.doc” only without any files maybe exist in that folder, so then you should REPLACE this code instead of gets each entry to be seems as follow:
// gets each entry
while($entryName = readdir($myDirectory)) {
if (strpos($entryName, ‘.mp3’,1) ) {
$dirArray[] = $entryName;
}
}
So, the files of mp3 will be displayed only
and if you want to display files of doc , or html , or wav, or ram , you should replac mp3 with any of them
Zeyad
But really i want some one to tell me how to limit this display , if the folder havre large quantities of mp3 files
and want to display 20 files per page when display in browsers
thanks in advance
Just came across this. Brilliant. Just what I wanted and as a beginner in php, a nice intro to some basic functionality.
Thanks.
File size change, bytes to Kbytes!
Replace:
with:
;)
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.