Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
As part of a image rotation script I use PHP to find all picture files in some directories and include them in a JavaScript array. Here is my current code:
<?php
function returnimages($dirname, $start) {
$pattern="(\.jpg$)|(\.jpeg$)"; //valid image extensions
$curimage=$start;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$dirname.''.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($curimage);
}$start = 0;
echo 'var galleryarray=new Array();'; //Define array in JavaScript
$start = returnimages("gallery/All Teams/", $start);
$start = returnimages("gallery/Varsity/", $start);
$start = returnimages("gallery/Junior Varsity/", $start);
$start = returnimages("gallery/Freshman/", $start);
$start = returnimages("rosters/", $start);
?>As you can see, I have to define sub-directories manually at the end of the script. Is there an easy way to have the PHP script automatically include all sub-directories inside of "/gallery/"?
-Ryan Adams
http://RyanTAdams.com

<?phpfunction returnimages($dirname, $curimage=0) {
$pattern="(\.jpg$)|(\.jpeg$)"; //valid image extensions
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){if (is_dir("$dirname/$file") && $file!='.' && $file!='..') {
$curimage = returnimages("$dirname/$file", $curimage);
} else {
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo "galleryarray[$curimage]='";
echo "'".str_replace('//','\\',$dirname)."\\$file';\n";
$curimage++;
}
}
}
closedir($handle);
}
return($curimage);
}echo "var galleryarray=new Array();\n"; //Define array in JavaScript
$start = returnimages("gallery/");?>
Michael J

I got that working by changing a few slashes and quotes. Here is the code that I have now:
<?php
function returnimages($dirname, $curimage=0) {
$pattern="(\.jpg$)|(\.jpeg$)"; //valid image extensions
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if (is_dir("$dirname/$file") && $file!='.' && $file!='..') {
$curimage = returnimages("$dirname/$file", $curimage);
} else {
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo "galleryarray[$curimage]=";
echo "\"".str_replace('//','\\',$dirname)."/$file\";";
$curimage++;
}
}
}
closedir($handle);
}
return($curimage);
}
echo "var galleryarray=new Array();"; //Define array in JavaScript
$start = returnimages("gallery");
?>Is there a way to define two directories?

This should work:
$start = returnimages("directory1");
$start = returnimages("directory2", $start);Michael J

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |