note 19021 rejected from function.readdir by sander
| From: | sander@php.net | Date: | Sat, 06 Apr 2002 19:16:39 +0000 |
| Subject: | note 19021 rejected from function.readdir by sander | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-28758@lists.php.net to get a copy of this message | ||
If you are reading this page then you are probably looking for a way to list a directory (and
it's sub dirs) and display it in your own pretty interface.
I expanded upon the above function "GetDirArray" so the contents of the directory and
it's siblings are returned in a multi dimensional array which mirrors the directory structure
;). Use this function and all you have to do is create an interface widget which feeds of an
array.... have fun.
<?
// MAKE DIR CONTENTS ARRAY FUNCTION
function make_dir_contents_array($PATH) {
// IF $PATH DOES NOT START WITH OR END WITH "/"
if (!ereg("^/",$PATH) ||
!ereg("/$",$PATH)) {
// RETURN FALSE
return FALSE;
// ELSE IF $PATH DOES START WITH AND END "/"
} else {
// OPEN DIRECTORY ($DIR_HANDLE) WITH SUPPLIED PATH
$DIR_HANDLE = opendir($PATH);
// EXTRACT THE NAME OF THE DIRECTORY FOR USE IN $OUTPUT ARRAY
$TEMP = explode("/",substr($PATH,1,-1));
$BASE_DIR = $TEMP[count($TEMP) - 1];
// LOOP ITEMS FOUND INTO $OUTPUT[$BASE_DIR] ARRAY
while (FALSE !== ($ITEM = readdir($DIR_HANDLE))) {
/* IF $ITEM DOES NOT START WITH "." PLACE INTO $OUTPUT[$BASE_DIR] ARRAY
("..",".",".htaccess" etc stop never ending loops via "."
and ".." nav directories)
*/
if (!ereg("^\.",$ITEM)) {
// IF $ITEM IS A DIRECTORY,
// CALL THIS FUNCTION TO PLACE IT'S CONTENTS IN ARRAY - RECURSSION IS THE KEY ;)
if (is_dir($PATH . $ITEM)) {
$OUTPUT[$BASE_DIR][++$INDEX] = make_dir_contents_array($PATH . $ITEM . "/");
//
// ELSE PLACE $ITEM INTO $OUTPUT[$BASE_DIR] ARRAY
} else {
$OUTPUT[$BASE_DIR][++$INDEX] = $ITEM;
}
}
}
// CLOSE DIRECTORY - KEEP IT TIDY
closedir($DIR_HANDLE);
// RETURN $OUTPUT ARRAY
return $OUTPUT;
}
}
// FULL PATH FROM YOUR SERVERS ROOT
$TEST_PATH = "/<the FULL path to your directory here/";
// PUT FUNCTION ARRAY OUTPUT INTO $DIR_CONTENTS
$DIR_CONTENTS = make_dir_contents_array($TEST_PATH);
// PRINT THE PRETTY ARRAY
// this is what you replace with your interface widget
print("<pre>");
print_r($DIR_CONTENTS);
print("</pre>");
?>