Choose random image from dir and display it

From: kingofkolt (jessepNOSPAM_at_comcast.net)
Date: 10/30/04


Date: Sat, 30 Oct 2004 01:04:54 GMT

I have a directory of images, called "random". In it are the following
files:

1.gif
2.gif
3.gif
4.gif

I use this script to choose a random image and display it:

$i = -2; // $i = -2 so that the directory files ("." and "..") won't be
counted.
if ( $dh = opendir( "images/random" ) ) {
 while ( false !== ( $file = readdir( $dh ) ) ) {
  $i++;
 }
 closedir( $dh );
 $rand = rand( 1, $i );
 $randimg = '<img src="images/random/' . $rand . '.gif" />';
}
print $randimg;

This works just dandy. However, I figure there must be a more efficient way
to count the number of files in a directory. Is there a directory's
equivalent of a function like file()? Or is my script the only way to count
the files?

Thanks.
- JP



Relevant Pages

  • Re: calling a php script using img src ="random.php"
    ... >> I am trying to call that in another page so that i get a random image ... >Your script does not return an image. ... You cannot link to an HTML page with the tag. ... individual gifs when the script was called. ...
    (comp.lang.php)
  • Re: im such a noob...
    ... i'm trying to write a very simple CAPTCHA script. ... random image as desired. ... script the image displays, say, "AAAAA", the bottom line displays "VAR ...
    (alt.php)
  • RE: Windows > Unix volunteers
    ... some people even just use cron jobs with a script to force a background change to a random image every X minutes. ...
    (freebsd-questions)
  • Re: Changing Picture automatically
    ... To load a random image each time the page is open would require a server side script. ... If you are hosted on an Apache/UNIX server with a web masters CPanel check the cgi ... > have a picture, but every time the visitor goes to the ...
    (microsoft.public.frontpage.client)
  • Mod_perl woes
    ... using mod_perl and CGI::Application for some pokey stuff, ... Following script works dandy: ... But this script only generates output in a CGI environment: ...
    (comp.lang.perl.misc)