I’m trying to write a script to read subfolders in an image directory. This is a bit beyond what I am able to do in php.
In my php code I am trying to read the main directory and then if the loop reads another directory, I am trying to open that and reads its contents as well. I’m not getting any errors per se, but by script in the ‘get subfolders’ portion of the code below is not working. Any suggestions? Thanks in advance.
$dir = '../images/';
// open the current directory
$dhandle = opendir($dir);
// define an array to hold the files
$files = array();
if ($dhandle) {
// loop through all of the files
while (false !== ($fname = readdir($dhandle))) {
// if the file is not this file, and does not start with a '.' or '..',
// then store it for later display
if (($fname != '.') && ($fname != '..') &&
($fname != basename($_SERVER['PHP_SELF']))) {
// store the filename
$files[] = (is_dir( "./$fname" )) ? "(Dir) {$fname}" : $fname;
}
}
//get subfolder contents and file names
if (is_dir($fname)) {
if ($dh = opendir($fname)) {
while (($file = readdir($dh)) !==false) {
echo "filename: $file : filetype: " . filetype($fname . $file) . "\
";
}
closedir($dh);
}
}
// close the directory
closedir($dhandle);
}
}
Then I echo out:
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $fname )
{
echo '<a href="' . $dir . $fname . '"><img src="' . $dir . $fname . '" width="140" height="100"></a>';
}
I was able to capture the subfolder contents. But now I am having trouble formatting my file path correctly for echoing. I need to echo out a certain structure of the array as given in my php comments - but cannot seem to do this with the array. Any help would be appreciated. Thanks!
$dir = '../images/';
// open the current directory
$dhandle = opendir($dir);
// define an array to hold the files
$files = array();
if ($dhandle) {
// loop through all of the files
while (false !== ($fname = readdir($dhandle))) {
// if the element is a directory, and
// does not start with a '.' or '..'
// passing this element as a parameter
if (is_dir( "{$dir}/{$fname}" )) {
if (($fname != '.') && ($fname != '..')) {
if ($dh = opendir( "{$dir}/{$fname}" )) {
while (($file = readdir($dh)) !==false) {
if (($file != '.') && ($file != '..') &&
($file != basename($_SERVER['PHP_SELF']))) {
//store subfolder and filename
//Need structure - $fname/$file for echo
$files[] = $file;
}
}
closedir($dh);
}
}
}
}
closedir($dhandle);
}
My echo script : I need to include the $fname (path name) in the scr tag, but not sure how to.
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $file )
{
echo '<img src="' . $dir . $file . '" width="140" height="100"></a>';
}
?>