|
||||||||||||||||||||||
Reading File Directories : Repeating FunctionsFunctions are a very important part of resuable code.
Retrieve Directory ListingThis function reads all of the files and subdirectories in a given folder, and returns a multi-dimensional array containing all the information.Each subdirectory is stored as a new layer.
<?php
function retrieveDirs($rootdirpath) {
$array = false;
if ($dir = @opendir($rootdirpath)) {
while ($file = readdir($dir)) {
if (is_dir($rootdirpath."/".$file) && $file != "." && $file != "..") {
$array [$rootdirpath."/".$file]
= retrieveDirs($rootdirpath."/".$file);
} elseif($file != "." && $file != "..") {
$array [] = $rootdirpath."/".$file;
}
}
closedir($dir);
}
return $array;
}
?>
A quick run through of how it works. Returned from the function is an array containing the list of files in the directory. Arrays can be stored within arrays. Sub folders are entered as arrays within arrays containing the list of files.
Note: The full path of the file is stored, not just the file name. Hence
Using the arrayOkay, thats great.. you can now read a whole directory tree into an array. How do you make use of this information? Lets display it on screen.
<?php
function echoArray($array, $level=1) {
foreach($array as $key=>$value) {
if(is_array($value)) {
echo "<h$level>$key</h$level>";
echoArray($value, $level+1);
} else {
echo "<h$level>$key : $value</h$level>";
}
}
}
?>
This repeating function echos each value in an array. If an entry is an array, then it goes into a sub-loop to echo that array.
Test the scriptYou can try this script out. Put it in the base of your web directory, include the two functions above.
<?php
// Include Directory and Array functions.
include("functions.php");
// Create array of files/sub-directories
$array = retrieveDirs('..');
// Echo array
echoArray($array);
?>
Closing wordsReading files from directories is dead simple. Just remember to close the directory after you've finished (can sometimes cause problems if you don't).Feel free to use the functions I made. They're quick to make and very useful. When you learn how to upload files to servers, you'll realise how important it is to manage files. Many websites already offer PHP based file management systems, but nothing beats being able to make your own.
Author: Markavian |
tutorial Pages
|
|||||||||||||||||||||