How-To Geek
PHP: Display a customizeable list of files in a directory
Apache gives you a list of files in an empty directory by default, but sometimes you will want to show a list of files that are in a directory through PHP so that you can customize the output of the list, and make a “pretty” listing of files. Here’s the basic code to make a list.
<?php if ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $thelist .= '<a href="'.$file.'">'.$file.'</a>'; } } closedir($handle); } ?> <P>List of files:</p> <P><?=$thelist?></p>
That’s about all you need to do. You could also put the list of files into an array if you felt like it, or use this as the beginning for a thumbnail page, which is what I used it for.
Got Feedback? Join the discussion at discuss.howtogeek.com
Comments (77)
Programmer by day, geek by night, The Geek, also known as Lowell Heddings, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on Google+ if you'd like.
- Published 09/25/06




I found that the following line needed a newline entry to make the list more readable:
$thelist .= ‘‘.$file.’
and also the last line seems not to work for me the way its coded above. just use echo $thelist; is fine.
Oz
Is there any way to make the list not list the php file generating the list?
The above code saved as “list.php” along with files “file.txt” “file2.jpg” “file3.html” will list 4 files: list.php file.txt file2.jpg file3.html
@Newb:
Replace:
if ($file != “.” && $file != “..”)
with:
if ($file != “.” && $file != “..” && $file != “list.php”)
That should work.
What about including the date and file size too?
You can use filesize() function to get the file size. To get the last modification date use filemtime().
Here’s an example:
List of files
$file, ‘filemtime’ => filemtime($file), ‘filesize’ => filesize($file));
}
}
closedir($handle);
}
?>
File nameFile SizeFile Last Modification Time
I don’t know why but the code doesn’t display at all. Anyway, here’s the code: http://pastebin.com/f24b4f242
OK, the below works great, but where do I add or what do I replace exactly to get the file time and date to show up.
Note I’ve added to exclude index.php file so it won’t display in list instead of the above which excludes list.php. I also changed ‘.$file.’ to ‘.$file.’ to give a carriage return after each file.
‘.$file.’‘;
}
}
closedir($handle);
}
?>
List of files:
This forum must be limited on comments size. Here is the full code:
‘.$file.’‘;
}
}
closedir($handle);
}
?>
List of files:
how would i go about adding the list of files(amount of which will vary) into a dropdown menu?
How can you make the list a list of hyperlinks? so that user can click on the file to open it.
anyone have some good style sheet / colored layouts that i could try out… i know very little of php, just a few commands for forms and i am trying to learn more
i have a directory full of web games already in html files, i want to make a php page that displays all the files in the directory but i want it to look kinda like a webpage
I’m trying to use this to make an archive of sorts.
I want it to list a certain amount of recent additions, with the oldest one being taken off from the bottom as new ones come up. I’ll have a link to the complete archives, where its the same concept, recent ones at the time, older ones at the bottoms, but limited to a certain amount per page and once that limit is reached, a new page is generated in addition to.
I’m a n00b at PHP though. Heh.
Thank you for this information. It helped me out a lot!!
Is there a way to deploy this script and use a drop-down menu to show the list of filenames?
like say you have a massive directory of MP3s… what im hoping to do is use the code above to gather the filenames, then place them in the drop-down list; so that each value is the file name…
@ David:
Sure, it defenitly is possible, quet easy excally.
Simply replace the last 2 rows with:
echo ‘
‘.$theList.’
‘;
and the part of:
$thelist .= ‘‘.$file.’‘;
Would be changed into:
$thelist .= ”.$file.”;
Should work out well, goodluck with it!
Whoops! Just reconized that this form doesn’t allow html…
So here are the same codes, only this time readable (hopefully) and you just need to replace the x into those things I forgot the name from at the moment.
xform action=”listen.php” method=”post” name=”mp3List”x
xselect name=”song”x
‘.$theList.’
x/selectx
x/formx
and the part of:
$thelist .= ‘xa href=”‘.$file.’”x’.$file.’x/ax’;
Would be changed into:
$thelist .= ‘xoptionx’.$file.’x/optionx’;
what about if I want the option to delete some of the file, by clicking delete, how can I doit?
Hi
Good, The Above Coding is Working
I made a couple changes to this. Now each link is on a different line and you can right click and save it.
Here it is:
—————
To download, right click on the link to the file you want to download and click Save as.
‘.$file.’‘;
}
}
closedir($handle);
}
?>
Here is a list of all the files that have been uploaded:
Hello;
This is great except my files are named
Ch1-a
Ch2-b
Ch3-c
ETC
The problem is that I have 10 of them, so the list is
Ch1-a
Ch10-a
Ch10-b
ch2-a
How can I fix
Hello, I was looking for something just like this, simple and concise, thanks a whole lot ! :)
To display all the files in list format and from another directory, i modified the code somewhat.
‘.$file.’‘;
}
}
closedir($handle);
}
?>
List of files in upload directory:
Hope this helps some of you
I have directory that gets images added to it each day. I want to list the 10 newest images, showing the images with links.
From that I can generate an rss feed, but I can’t figure out the PHP for this.
This list is working great, but I would like to change the order to display alphabetically instead of oldest-newest. Is this possible?
Code works great, thanks guys! One question, is it possible to modify the code so that it displays ONLY files starting with a specific sequence of letters, or displays only files in the directory ending with a specific extention? Thanks :) :) :)
Great workd. It worked for me. How do I list the one file per line?
The script is great. Works flawlessly
Is there any way to list the files into a table, on 2 columns?
file 1 file 2
file 3 file 4
and so on…..my idea is simple…but i’m not such a big programmer, so…
insert all file names into a array, count array, and then output with a “for” or “while”.
but as I said….I need someone to make it into a script, my head already hurts from this :)
Thanks in advance
‘.$file.’ ‘;
$i++ ;
}
}
closedir($handle);
}
echo ”
$y=0
foreach ($thelist As $listitem) {
echo ”$listitem,”;
if ($y=1) {
$y=0;
echo ”;
} else {
$y=1;
}
}
echo ”
?>
forget my previous post:
‘.$file.’ ‘;
$i++ ;
}
}
closedir($handle);
}
echo ”;
$y=0;
foreach ($thelist As $listitem) {
echo ”,$listitem,”;
if ($y==1) {
$y=0;
echo ”;
} else {
$y++;
}
}
echo ”;
?>
‘.$file.’ ‘;
$i++ ;
}
}
closedir($handle);
}
echo ”;
$y=0;
foreach ($thelist As $listitem) {
echo ”,$listitem,”;
if ($y==1) {
$y=0;
echo ”;
} else {
$y++;
}
}
echo ”;
?>
Hi,
I can’t get this to work. Where exactly do I place it in my code? I’m very new to PHP.
Thanks!
Kristen
Hi,
Great piece of scripting, works just great :D
I liked Lumex’s idea of using it for another directory, however in his post it does not become clear how to do so, so i did some research myself and all the people who would like to do so.
It is actually very easy. All you have to do is replace this line:
if ($handle = opendir(‘.’)) {
with this:
if ($handle = opendir(“your/directory/”)) {
(replace your/directory/ with your own directory, relative to the file in which the whole piece of php code above is used.)
Greetings from the Netherlands :)
Hi there,
Is there a way to exclude the file type?
Like “Page.php” to display only “Page”?
Is there a way to add password protection to the files, I have a website that I want people to be able to download files i upload to a directory but only after they have entered a password
I can’t get the exclusion code to work. I’m trying to exclude certain file types from being displayed when I display the directory contents. For instance, the index.php file.
Kirsten:
Just insert the files like:
Like what?
Just insert the files like:
?php
if ($handle = opendir(‘.’)) {
while (false !== ($file = readdir($handle)))
{
if ($file != “.” && $file != “..”
&& $file != “NOT-TO-BE-IN-1.php”
&& $file != “NOT-TO-BE-IN-2.html”
&& $file != “NOT-TO-BE-IN-3.jpg”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
)
Or have a look at: http://www.php.net/readdir There is almost anything you want there.. Cant find it now but there is code snips that you can choose whitch file types should be displayed.
I have a problem with the arrangement of the list.
I have a problem with the arrangement of the list.
Example:
1.php
10.php
100.php
2.php
21.php
3.php
I would like it to display:
1.php
2.php
3.php
10.php
etc.
The code by Ege does not work.
@Eugene;
because it didn’t show up properly when I copied and pasted it. I will upload it as a text file and post the link here as soon as I get back home (which will be in two days)
Great! Thank you so much Ege!
Thank you very much! that would be great!
well Eugene…
about the order u wanted to display…
it can’t be helped if u want to keep the file names just like that…
because names are read as strings & not numbers…
if u want 1,2, 3…10, 11, 12…21, 21, 23…
then u will have to rename files as 01, 02, 03 & so on :)
hope this helps
Thanks will try that!
Ok so basically I want something that will find out what files are in a folder and then php include them into a previously built page.
Eg. listed/1.php
listed/2.php
listed/3.php
would show up as
Now I could do this myself but I am expecting 100′s of files that require including. This is what Ive got.
‘.”;
}
}
closedir($handle);
}
?>
List of files:
I think it has a problem using the
grr code doesnt show up properly in here. Never mind.
sort($file);
For Accending order of file.
What if i want to check if there are files in that dir
can someone help me with a script of getting only mp3 files with download link?
thanks
How do I organize my list of files by name? I’m not sure what order they are in now, but I’d like it by name.
I created a way to remove certain text or at least the extension from the names on list. I havent implemented it to the actual code, but I think it will be easy to do so, heres it:
Hope it helps
I know this is an old thread, but had a quick question for this. Ive created this to create a list of newsletters in a directory. It works a treat however i was wondering if there was a way I could limit this to just show the first 5 entries int he folder, else it starts messing with the layout.
My idea was to show the top 5 files on the main page, then have a link to view all past newsletters
I used to do a little bit of programming but very new to PHP and cant quite get my head around where in the code this additional count would go
Thanks
Here is How to populate a dropdown Menu with a directory :
//
// <?php
// $dir = ".";
//
// Open a known directory, and proceed to read its contents
// if (is_dir($dir)) {
// if ($dh = opendir($dir)) {
// while (($file = readdir($dh)) !== false) {
// print "{$file}”;
// }
// closedir($dh);
// }
//}
//?>
//
hmm, the above code left out the html portion it goes inside.
select name=”menu1″
**** the php code above goes in here *****
select
Remember to put the >< around the select tags.
I found out that you need to change the quote manually to make it works when you copy paste.
change the ” and ‘ using you own keyboard
hello to everyone. im a newbie in PHP and APACHE. actually im still a student. my problem is my thesis is kinda similar here, “File management”. i finished the upload already, but my i dont know how to work on the file list and file download. please help me. i need to pass my thesis. thanks in advance.
Here is an example with an array and sorting alphabetically. It is very basic but you could help.
<?php
$currdir = "./pdfs/Investor Newsletters/";
$thelist = array();
if ($handle = opendir($currdir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
array_push($thelist, '‘.$file.’‘);
}
}
closedir($handle);
}
sort($thelist);
foreach($thelist as $value)
{
echo $value;
}
?>
good luck folks!
Here is an example with an array and sorting alphabetically. It is very basic but it could help. (please ignore my first comment)
<?php
$currdir = “./pdfs/Investor Newsletters/”;
$thelist = array();
if ($handle = opendir($currdir)) {
while (false !== ($file = readdir($handle)))
{
if ($file != “.” && $file != “..”)
{
array_push($thelist, ‘<li><a href=”‘.$currdir.$file.’” target=”_blank”>’.$file.’</a></li>’);
}
}
closedir($handle);
}
sort($thelist);
foreach($thelist as $value)
{
echo $value;
}
?>
If I want to generate link to different folder what should I do?
example: folder1: test.doc link to folder2: test.html
Thx before
sorry to say but ur code do not work properly.
actually i want printing all the sub folder name and contents of each folder of the main directory anyway thx.
How would we be able to remove the .php file extensions and just have the file name there?? Cuz I don’t want my user’s to see the “.php” part of the file until they have clicked the link and entered into the file.
Thanks a lot! Yours script very helped me
it is the code for search a file in folder directory?
for example i input a the ID num# of a student in the text field then it search a ID num of a student in directory file in folder .
plss help me! thx …
How secure is this and how do you add security to this script
Hi,
I was just wondering if you knew of a way to display a list of image from a folder that all had the same first 4 characters in the file name:
display:
1111_picture1.jpg
1111_picture2.jpg
1111_picture3.jpg
exclude
2222_picture1.jpg
2222_picture2.jpg
2222_picture3.jpg
I hope this makes sense?
i like this blog. wish you best of luck. See you later Vacation Accrual
sorry for asking this, I just a newbie on this php. from above , what should I change or add to show the files in order line by line?
this orignal code is great for me, however, all files or folders in the directory I launch the code; it just shows all files/folder names side by side.
Appreciate for help.
Thanks!
I’m getting errors and am still new to php. can anyone help me my exicutable is running from the following location mysite.com/tools/index.php and needs to be able to list files in a folder at a deeper level the folder location is from the md5 of the user_ID and is in the folder users. from the main page I need to create the folder if it doesn’t exist and if it does I need to list what ever is in it. I know how to do it in VB but for the life of me I can’t figure it all out in PHP. this is the script I have so far:
//
//
// <?php
//$thefolder = md5($_SESSION['SESS_MEMBER_ID']);
//myfolder == ("/users/".$thefolder."/");
//if(is_dir($myfolder))
//echo "directory exists for user ID ".($_SESSION['SESS_MEMBER_ID'])."”;
//else
//{
//mkdir(“\\users\\”.$thefolder,0777,TRUE);
//echo “folder created named: “;
//}
//echo”\\users\\”.$thefolder.”";
//?>
//
//<?php
// if ($handle = opendir($myfolder)) {
// while (false !== ($file = readdir($handle)))
// {
// if ($file != "." && $file != "..")
// {
// $thelist .= '‘.$file.’‘;
//}
// }
// closedir($handle);
// }
//?>
//List of files:
//
I would like to get this working without errors and with the main page its running from working again but the errors are shutting down the java scripting from the main page as well and I just don’t get why it isn’t redirecting to the folder that needs to be opened. I’ve populated the folder and get an error that says the following:
Warning: opendir(./user/fad7db368a905c0a9320aef3392a19fd/) [function.opendir]: failed to open dir: No such file or directory in /home/content/15/7439815/html/tools/desktop.php on line 20
what have I done wrong?
Thanks for the review.
it’s very interesting and full of handy features..
Hello!
I’ve been tinkering with code, and its almost perfect!! I’m just having two issues:
-I want it in aphabetical order
-I want the file names to be links.
I see three different codes up there doing three different things, but I haven’t been able to successfully combine them.
Help?
List of files
$file);
}
}
closedir($handle);
}
?>
File Name
<?php
for($i = 0; $i
(Continued apparently)
List of files
$file);
}
}
closedir($handle);
}
?>
File Name
<?php
for($i = 0; $i
Here is a simple modification that I made to the original code in the article.
-The output is one file name per line.
-Each file name is a hyperlink to the file.
-The files listed is in the same directory as the index.php file.
-The list does not show the index.php file in the list.
-The list is not alphabetized.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != "index.php")
{
$thelist .= '‘.$file.’‘;
}
}
closedir($handle);
}
?>
List of files:
The change made is in the 7th line of code.
Original:
$thelist .= ‘‘.$file.’‘;
Modification:
$thelist .= ‘‘.$file.’‘;
Thanks for the original bit of coding and the suggestions above that helped me get what I needed out of this list.
NOTE: This works on my system, you may have to tweek the code a bit to get the desired output for your system.
Update: The post did not include the mods.
//<?php
// if ($handle = opendir('.')) {
// while (false !== ($file = readdir($handle)))
// {
// if ($file != "." && $file != ".." && $file != "index.php")
// {
// $thelist .= '‘.$file.’‘;
// }
// }
// closedir($handle);
// }
//?>
//List of files:
//
//
The change made is in the 7th line of code.
Original:
// $thelist .= ‘‘.$file.’‘;
Modification:
// $thelist .= ‘‘.$file.’‘;
Thanks for the original bit of coding and the suggestions above that helped me get what I needed out of this list.
NOTE:You will need to remove the // from each line of code to get it to work on your system.
NOTE: This works on my system, you may have to tweek the code a bit to get the desired output for your system.
Grrr…
in short… since it didn’t show up twice….
Add the “” and the “” to line 7 just before and after the file reference.
if ($file != “.” && $file != “..” && $file != “list.php”)
but what if i want to exclude a specific type of files, like, all “.txt” files. Then what should i do? Im a newbie,so 4give my idiotic question and answer pls.
Any way to display only .mp3 files in the directory (don’t show .htaccess, error_log, folders…)