Hi

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>

</div>


Is there any php that will change the image randomly?

Thanks in advance

Tankedup

Recommended Answers

All 5 Replies

The simplest would be something like this

<?php
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.'" />
         <em>Image'.$rand.'</em>
    </span>
</a>
</div>
';
    $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 :)

whoops, delete line 9, that was a little booboo

Yet another function to display random images:

<?php

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

   randomize();

?>

$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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.