Page 1 of 1

Randomly Pick image from a folder and display

Posted: Tue Mar 18, 2008 6:11 pm
by mrme
I want to be able to randomly pic an image from a set folder, and then display.

A while back (coupla years), my old boss created this code for me.

Code: Select all

<?
$imagetopcount='1';
$dir="ads/top_rotator";
$webpath="ads/top_rotator";
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
            if ("$file"!="." && "$file"!="..") {
                srand((float) microtime() * 10000000); 
                $image[$imagetopcount]="$webpath/$file";
                $imagetopcount=$imagetopcount + 1;
            }
       }
       closedir($dh);
   }
}
$rn = array_rand($image); 
echo "<div align=\"right\"><img src=\"$image[$rn]\" width=\"331\" height=\"185\"></div>";   
?>
Which works great! It will randomly pick an image from the folder "ads/top_rotator" and display it.

The problem comes in when i try to run the script twice on one page. The second script is adjusted to select a picture from a different folder, as follows.

Code: Select all

<?
$imagetopcount='1';
$dir="ads/vert_ad_160x300";
$webpath="ads/vert_ad_160x300";
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
       while (($file = readdir($dh)) !== false) {
            if ("$file"!="." && "$file"!="..") {
                srand((float) microtime() * 10000000); 
                $image[$imagetopcount]="$webpath/$file";
                $imagetopcount=$imagetopcount + 1;
            }
       }
       closedir($dh);
   }
}
$rn = array_rand($image); 
echo "<div align=\"right\"><img src=\"$image[$rn]\" width=\"160\" height=\"300\"></div>";   
?>
The problem i am running into is for some reason the second script will pick a image from the folder "ads/top_rotator" about 50% of the time. I have been working on it all day, changing variables, folder names, researching arrays and such, and no luck. :banghead:

I am not a newb, but i am not real proficient in PHP yet, and could really use some help. I have been lurking for a while, and can find my answers most of the time, and have learned a lot from everybodys post, so thanks!

Any help on this piece of code would be a great help!!

Thanks

Re: Randomly Pick image from a folder and display

Posted: Tue Mar 18, 2008 6:19 pm
by scriptah
Ok, first of all, this code is seriously old ... still seeding in order to generate random numbers, that's archaic ;)
The best thing you could do for yourself is to rewrite this piece of code, and use a function instead ...

Like:
getRandomPictureFrom( $path ) { ... }

Try removing the following line from the second script:

Code: Select all

 
$imagetopcount='1';