Folder contents - PHP & MySQL tutorial
- Added: Oct 13th, 2006
- Level: Medium
- Author: Melfina
- Reads: 12,838
- Description: Output all files within a folder
With a few lines of code, we can output all the images within a folder. Changing this simple code a bit, we could also list text files, zips... whatever you have on your folder, but we will be doing it now with images, so whatever folder you use, it should be filled with images only, the extension doesn't matter. Please see the number next to each line of code for more information below.
<? $folder = "path_to/your_folder"; //1
if ($handle = opendir('$folder')) { //2
while (false !== ($file = readdir($handle))) { //3
if ($file != "." && $file != "..") //4
echo "<img src=\"$folder/$file\" alt=\"\" />"; //5
}
} ?>
Explanation on each line:
- Change to your folder name and path relative to the script where you place this piece of code.
- Open your folder.
- Run the script while there are files within the folder that hasn't been already output.
- Ignores the files "." and "..". This has nothing to do with the names of the files you've got on your folder but sctrictly server commands. "." means this directory and ".." parent directory. You shouldn't worry about this anyway.
- Code for each image. Here you can add width, height, alt or add a class but remember to escape all quotations with a backslash ("\")
Basically what it does is open the folder and read all the contents within it and output each one with a loop until there aren't any other files. It's all commented above.
To use it with other kinds of documents you just need to change the echo to, for example an url, like this:
<?php echo "<a href=\"$folder/$file\">$file</a>"; ?>
If you like this tutorial why not digg it or add to del.icio.us?
Tutorial © Melfina. Do not reproduce in any way without previous permission from the author.