Latest TweetsVerify any search engine or visitor via CLI Forward-Reverse Lookup perishablepress.com/cli-forwar…
Perishable Press

Drop-Dead Easy Random Images via PHP

Recently, while restoring my collection of Perishable Press themes, I needed a fast, effective way to randomize a series of images using PHP. After playing around with several possibilities, I devised the following drop-dead easy technique:

<img src="http://domain.tld/path/random/image_<?php $random = rand(1,n); echo $random; ?>.png" alt="[ Random Image ]" height="50" width="50" />

This single line of code facilitates the random display of n number of images (image_1.png, image_2.png, image_3.png, etc.) located in the target directory (http://domain.tld/path/random/). For those of you that understand how this works, great! That’s pretty much the entire purpose of this article. However, for those that would appreciate some further explanation, let’s examine this technique in a little more detail (you have been warned!)..

Update: Check out my related tutorial, Get Random with PHP »

Step 1: Prepare your images

Prepare any number of images of the same file type (e.g., .png, .jpg, .gif, etc.) and name them numerically. You can name your images just about anything you like, so long as the only difference between each name is a single numerical digit. Further, ensure that the numerical digits begin with zero and proceed in order to the total number of images in the set. For example, assuming you have three .png images, any of the following name sequences is perfectly acceptable:

  • image_1.png
  • image_2.png
  • image_3.png

..or:

  • random-image_01.png
  • random-image_02.png
  • random-image_03.png

..or:

  • 1.png
  • 2.png
  • 3.png

..or just about anything, so long as it follows this general pattern. With a little imagination, it is even possible to use images of different file types, but I will leave that as an exercise for my readers. ;)

Step 2: Prepare the code

Once you have a properly named series of images, upload them to your server and break out with your favorite text editor and prepare to write some code! Once again, here is an example of the final code that we will be using to display our random images:

<img src="http://domain.tld/path/random/image_<?php $random = rand(1,n); echo $random; ?>.png" alt="[ Random Image ]" height="50" width="50" />

How do we get there from here? Easy. First, determine the path of your random image directory. For this tutorial, we’ll assume that the images are located at http://domain.tld/path/random/. Given this information, we can begin writing our randomizing code as follows:

<img src="http://domain.tld/path/random/" />

That’s what we know so far. Now, let’s assume that we are using the “image_n.png” format for our file names, where n equals the particular number of the image. With this information, we may continue with our previous code:

<img src="http://domain.tld/path/random/image_n.png" />

Of course, we may now use PHP to replace the n with a randomly generated number, ranging from 1 to the total number of images in the directory, say 3 for this example. After replacing the n with our randomizing PHP function, we have:

<img src="http://domain.tld/path/random/image_<?php $random = rand(1,3); echo $random; ?>.png" />

Thus, to dynamically randomize the n in our previous example, we are using this little bit of PHP bliss:

<?php $random = rand(1,3); echo $random; ?>

..where 3 represents the total number of files in the random image directory. With this in place, we are generating and echoing a single random number, thereby changing the file name with each page load. Nice.

Step 3: Make it all sweet

Last but certainly not least, we need to complete our code with a few important details. First, you will want to add an alt attribute (and perhaps even a title attribute as well):

<img src="http://domain.tld/path/random/image_<?php $random = rand(1,n); echo $random; ?>.png" alt="[ Random Image ]" />

And then finally, if all of your images are of the same size, it is a good idea to facilitate browser rendering by specifying both the height and width, say 50 pixels square in this case:

<img src="http://domain.tld/path/random/image_<?php $random = rand(1,n); echo $random; ?>.png" alt="[ Random Image ]" height="50" width="50" />

Of course, if your random images are not uniformly sized, simply omit this last step. In either case, once you have finished adding the requisite attributes, the randomizing code is complete. Now is the time to upload your document and check that everything is working as intended. If everything lines up as it should, your page should display a random image with each visit.

If, for some reason, things don’t exactly “click” as expected, go back through each step and ensure that every detail has been accounted for. You would be surprised how many times I have tested something like this only to discover that some infinitesimal detail is out of place. Check the file path, file names, PHP script — everything! While I don’t expect anyone to experience difficulty with this code (it is pretty simple, after all), I do want to make everything as clear as possible to facilitate the successful implementation of this technique!

Whew! Am I long-winded or what? Hopefully, I didn’t put anyone to sleep during this one! ;)

Jeff Starr
About the Author Jeff Starr = Creative thinker. Passionate about free and open Web.
Archives
26 responses
  1. Jeff Starr

    Good question, Carlo; I wish I could help you, but I am not familiar with the PHP3 extension. One thing’s for sure, the randomization script is nothing heavy; a little testing should reveal the answer.. I know it works great on “regular” PHP..

  2. Thanks for your reply Jeff. I’ve tried a couple of things and couldn’t get it to work on my friends server which only supports php3. Actually, this code works fine on the server my site resides. However, I stumbled on a javascript that works perfect so I stopped trying to figure this code out.

    Thanks again.

  3. SneakyWho_am_i September 26, 2008 @ 3:14 pm

    The error message would have helped to figure out whether it would work, even if he gave up as soon as he saw it. Then again… it’s php three

    Even PHP4 is no longer being maintained, and I suspect that php5 is 4 years old now!

  4. Jeff Starr

    Is that what Carlo meant by “php3”? I was just taking a wild guess that he was talking about compressed PHP files or something.. It never occurred to me that he was referring to PHP 3! I honestly don’t go back that far; for me, the universe began with PHP 4. I can’t even imagine what PHP 3 must have been like..

  5. I, too, have copied your code; however, it is not working for me. Do you mind helping me out?

    Thanks!

  6. Hi, I like this code. How to make it work for more images without repeating?

    if u have 6 pictures to show up for example, u can create 6 different folders and do 6 lines ( no repeat guaranteed) – but I think it is stupid kind of way.

    What about how to do 6 random pictures from 1 folder without repeating?

    Anyone knows?

  7. Jeff Starr

    @Leprakawn: I will do my best to help, but keep in mind that the article represents about the most basic way I know how to share the technique.

    @Radek: I will have to look into that.. never seen it before..

  8. …or posibility to do that in case it is easier with mySql, pictures in database, pick (non-repeating) 6 pictures and throw them on the screen….

  9. Jeff Starr

    Sure, that would be great — be sure and share the technique with everyone if you find a solution! ;)

  10. I would but I am looking for one :)

  11. Jeff Starr

    Have you tried Google?

    “non-repeating random images php”

    Yields many results..

  12. I really like this idea, but I need it to occur during and onclick event. A client has asked me to have his normal pop up window ,which now displays his newest product, to now pull randomly from a folder in which he can drop images into.

    What needs to go in the head of the html doc? What needs to be present at the onclick event?

[ Comments are closed for this post ]