16 Mar 2010

Simple PHP Random Image Script

PHP No Comments

There are times when working with smaller sites you need a simple method of displaying random images. This can be done in one line of text directly in your HTML and a collection of images.

Prepare the Images

The first step is to gather together the images you wish to have randomly rotated. Change all of their file names to a numerical order, starting with the number 1.

  • 1.jpg
  • 2.jpg
  • 3.jpg
  • 4.jpg

Be sure each image has the same extension (either all jpg, png, or gif), and that there are no gaps in the numbers. Also, place these images in their own folder to keep everything organized.

Write the Code

Now in the HTML of your page, insert the following code where you want an image to display:

<img src="/path/to/<?php echo rand(1,n);?>.jpg" alt="Random Image" />

The “rand” operator will display a randomly generated number between 1 and ‘n’. Change ‘n’ to the total amount of pictures you have arranged numerically (or the highest numbered picture you have). In the example above I only have 4 pictures, therefor I would change it to: rand(1,4);

To finish it off, change ‘/path/to/’ to the path your stored the images in.

No Responses to “Simple PHP Random Image Script”

Leave a Reply