Forum Moderators: coopster
Here's what I have:
$dir = $_SERVER['DOCUMENT_ROOT'] . "/foo/foosubdir/";
$handle = opendir($dir);
while (($filename = readdir($handle)) == true) {
$file_array[] = $filename;
}
--------
The above works fine in returning a list of folders found within "foo." The portion below is supposed to then look thru each folder in "foo" and return a list of files each folder contains. Instead it simply searches the current directory (which isn't "foo") and the site's root directory.
---------
foreach($file_array as $item){
$handle_sub = opendir($item);
while (($filename_sub = readdir($handle_sub)) == true) {
$file_arraysub[] = $filename_sub;
}
foreach ($file_arraysub as $itemsub){
print ($itemsub . "<br>");
}
}
Any help would be much appreciated. Thanks!
Mid. <-- php noobie
I'm so embarrassed to keep coming back with noobie questions, but here's another one.
Apparently the elements from the second array are getting returned for each iteration of the first array. In other words, it's returning something like this:
directory
directory
- subdir1
directory
- subdir1
- subdir2
and so on...
I assume this might be related to Robber's comment about closedir. Will closedir get the looping under control? If so, where would it go?
Thanks (again!)
Mid.
Have you tried using closedir to see what happens? Are you echoing the values of your first array before you actually use the data in your second array? Can you post us the code that is giving you the results shown?
As far as echoing the values of the array... I must have done that incorrectly too. It's still looping ad nauseum.
Thanks for taking a look at this!
<?php
$dir = $_SERVER['DOCUMENT_ROOT'] . "/foo/foosubdir/";
$handle = opendir($dir);
while (false!== ($filename = readdir($handle))) {
echo $filename;
$file_array[] = $filename;
}
sort($file_array);
reset($file_array);
foreach($file_array as $item){
$handle_sub = opendir($dir . $item);
while (false!== ($filename_sub = readdir($handle_sub))) {
$file_arraysub[] = $filename_sub;
}
foreach ($file_arraysub as $itemsub){
print ($itemsub . "<br>");
}
}
closedir($dir);
?>
You should only use readdir on directories.
You should use closedir with a the handle returned
from opendir.
<?php
$dir = $_SERVER['DOCUMENT_ROOT'] . "/stuff/";
$handle = opendir($dir);
while (false!== ($filename = readdir($handle))) {
if(eregi("^\.+$",$filename)) continue;
echo "TOP[".$filename."]<br>\n";
if(is_dir($filename)) $file_array[] = $filename;
}
closedir($handle);
sort($file_array);
reset($file_array);
foreach($file_array as $item){
$handle_sub = opendir($dir . $item);
while (false!== ($filename_sub = readdir($handle_sub))) {
if(eregi("^\.+$",$filename_sub)) continue;
$file_arraysub[] = $filename_sub;
}
closedir($handle_sub);
foreach ($file_arraysub as $itemsub){
print ( "$item : " . $itemsub . "<br>");
}
}
?>