A Quick and Dirty Way To Randomize an Image
Published by Guest Author
Here is a little trick for randomizing banners on your website. A bit quick and dirty. It needs to be on a PHP page to work.
First off we need to setup a folder on your server where the pictures will go. We need to name the pictures in order, for example, mypicture1.jpg, mypicture2.jpg and mypicture3.jpg and so on.
The next step is to edit your banner code on your website to reflect your new image files location. If you had...
<img src="http://www.yoursite.com/random_images_folder_path/mypicture.jpg" />
It would turn into...
<img src="http://www.yoursite.com/random_images_folder_path/mypicture<?php echo(mt_rand(1,3)); ?>.jpg">
MT_Rand is a PHP function that randomizes from a first number to a number, in our example 1 to 3. You can have it as high as you have pictures (since you can't randomize what you don't have).
You could also put this image in a PHP file, perhaps called mypicture.php, and include it into your banner area. That way you only have to change it in one place.
So open a new txt file and input the above random image code. Save the text file as a .php extension to your server. Then in your picture area include this code below.
<?php include("http://www.yoursite.com/mypicture.php"); ?>
You also don't have to use absolute paths. I did this for brevity and simplicity sake.
Well that all there is to that. Hope this helps someone.
This post was authored by Chris St. Amand. Chris has been freelance web designer and developer for the past 8 years.