Reading Directorys with PHP
(Page 1 of 2 )
A quick tutorial on how to read in the contents of a directory and display them.
By : Sliver
In this tutorial I'm going to show you how to create a directory reading system. A directory reading sytem will display all the contents of the specified directory automatically w/o you having to change your index file.
You can use this for things like an mp3 list so that if you frequently change the contents of your mp3 directory you dont have to change your index page all the time.
Lets look at the first bit of code:
<TABLE ALIGN=CENTER BGCOLOR=#ffffff CELLPADDING=4 CELLSPACING=0 BORDER=2> <tr><TH>File</TH><TH>Size</TH></TR> <?php $dir="./"; if (is_dir($dir)) { |
First we define our table and headings. Then we start the script. Next we specify the directory to read(./=current directory). Last we check if the directory is a valid directory.
$fd = @opendir($dir); if($fd) { while (($part = @readdir($fd)) == true) { if ($part != "." && $part != "..") { $file_array[]=$part; } } } |
Now we set a variable value to open the dir. After that we loop through the dir and name $part to the file name. Next we set an arrays value to $part(wich is the files name). Finally we close the if and the loop.
sort($file_array); reset($file_array); |
This sorts the array alphabetically.
for($i=0;$i<count($file_array);$i++) { $npart=$file_array[$i]; if (!strstr($npart,".inc.php") && !strstr($npart,"index.php")) { $fsize=filesize($npart)/1000; |
This starts a loop makes a new variable called $npart and sets it to the file_arrays value. Next we make sure its not an include file and it is not the index file if its not we get the file size and put it into kilobytes.
if (!strstr($npart,".inc.php") && !strstr($npart,"index.php")) { $fsize=filesize($npart)/1000; if (is_dir($npart)) { print("<tr><TD><a href=\"$npart\">$npart</a></TD><TD>Directory</TD></TR>\n"); } else { print("<tr><TD><a href=\"$npart\">$npart</a></TD><TD>$fsize KB</TD></TR>\n"); } } } } ?> |
Now we check if it is a directory. If it is it prints a link to it and in the size column it prints Directory. If it is not a directory we print a link to the file and print the size of the file in KB(or kilobytes).
Next: The final code >>
More Programming Basics Articles
More By Codewalkers