I know it's possible to have random backgrounds with php (day of week), but is it possible to have random images in a photo gallery?

I've written the html below:

<div class="thumb">

<a href="image01.html"><img src="images/image01_thumb.gif" alt="Image01" />

<span><img src="images/pre_image01.gif" alt="Image01" /><em>Image01</em></span></a>


Is there any php that will change the image randomly?

Thanks in advance


9 Years
Discussion Span
Last Post by tankedup

The simplest would be something like this

function randomImage($numImages = 10)
     srand( time(NULL));
     $rand = rand()%$numImages;
     $ranImage = '<div class="thumb">
<a href="image'.$rand.'.html">
    <img src="images/image'.$rand.'_thumb.gif" alt="Image'.$rand.'" />
    <span><img src="images/pre_image01.gif" alt="Image01" />
<img src="images/pre_image'.$rand.'.gif" alt="Image'.$rand.'" />
    $echo $ranImage;

Then wherever you wanted the image to display you would just do <?php randomImage(10); ?> . Given that you have 10 images that is. Also note that there is most likely a way to format a number to have the leading zeroes but I can't think of it off the top of my head.


Thanks ShawnCplus for the (very) quick reply! I'll have a go at it later tonight.

Thanks again, I must come here more often :)


Yet another function to display random images:


   function randomize() {
      $path = $_SERVER['DOCUMENT_ROOT'] . "images/";
      $dir = isset($_SERVER['DOCUMENT_ROOT']) ? $path : NULL;
      $filez = glob($dir . "*.jpg");
      echo '<img src="/images/' . str_replace($dir , '', $filez[0]) . '" />';



$path is where you put your images, then I check if $path is set and if it's ok I use glob to find all JPEG in the path ($dir variable, you can change it with gif or whatever). Finally, I use shuffle to randomize the order of the array ($filez variable). Bye :)


I suspect this may be a lot more complex than I envisaged. It may help if I give you the gallery address http://www.tankedup-imaging.com/css_dev/opacity.html

The problem I'm having is changing both the thumbnail and center preview to the same image. Maybe it's not possible as is, I've had a go with no luck, but am suffering from an England football post match hangover :)

I'll have another try tomorrow.

Thanks for all the feedback.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.