Drop-Dead Easy Random Images via PHP

by Jeff Starr on Wednesday, April 16, 2008 26 Responses

Recently, while restoring my collection of Perishable Press themes, I needed a fast, effective way to randomize a series of images. After playing around with several likely candidates, I finally 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!)..

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 like so:

<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 this:

<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 refresh of the browser window. 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! ;)

About the author

[ Jeff Starr ]

Jeff Starr is a web developer, graphic designer and content producer with over 10 years of experience and a passion for quality and detail. Jeff is co-author of the book Digging into WordPress and strives to help people be the best they can be on the Web. + Follow Jeff on Twitter and subscribe to Perishable Press for quality web-design content delivered fresh.


26 Responses
[ Gravatar Icon ]

Louis#1

Clean tutorial as usual. Though, I would split the PHP so that it’s no all in the HTML.

I mean, I would have that PHP code at the top of my PHP file.

I’d have then just the call in the HTML below.

<img src=”http://domain.tld/path/random/image_.png” alt=”[ Random Image ]” height=”50″ width=”50″ />

Like CSS separate presentation from content, I would separate the PHP calculations from the HTML.

For such a little task you do, it’s almost useless, but if we want for example to have the width & height of our images stored in arrays and use them to have the different heights & widths of our random images generated in the HTML, then we’ll find more comfortable separating the code and the output.

But again, clean tutorial :)

[ Gravatar Icon ]

Perishable#2

Yes WordPress can’t seem to take a hint when it comes to code left in comments (keeps gobbling everything up!).. If you have to leave a comment that contains code, simply use <code> tags to wrap each string of characters or else each line (if necessary). For some reason, this configuration of WordPress does’t like code wrapped in <pre> tags in the comments section, but <code> seems to work just fine.

[ Gravatar Icon ]

Gabe#3

Love it dude, great tutorial. I was thinking along the lines of Louis, too, separating the php from the html as much as possible. Additionally, I’d use a css class if all my images had the same dimensions, and put the width/height and any other style(s) in my css file. Something like this:

<?php $imgVar = rand(1,n);?>
<img src="<?php echo $imgVar;?>.png" alt="[Random Image]" class="randomImg">

Great snippet, thanks for the idea!

[ Gravatar Icon ]

Johann#4

I’m afraid I don’t like your approach that much. First height=”50″ and width=”50″ shouldn’t be in the markup but in the stylesheet, secondly, your alt-text ([Random Image]) is just plan wrong. How can someone grasp the meaning of your image with [Random Image]? I can’t. An empty alt-text (alt=”") would be probably better.

[ Gravatar Icon ]

Louis#5

Johann : adding the dimensions of an image directly in HTML has some advantage over writing it in CSS, i.e on page loading your image won’t “push” the text down them as they are loaded, there will be a 50*50 container keeping the place for them.

It seems to me that your are suggesting that the dimensions of the image should be in the stylecheet because it’s part of the layout. It’s not true : images are fixed content, they have a certain amount of pixels.

If the width & height attributes are accepted in XHTML 1.0 strict, that is for some reason I believe.

About the alt attribute, I’m not sure that an empty alt would be better than labeling the images “Random image”. After all, it is a random image. I guess it all depends on what the semantic sens of your random image is.

[ Gravatar Icon ]

Louis#6

If you can read french, there is a very exciting discussion on whether or not we should specify the width & height of images within the XHTML or inside the CSS here:

http://www.blog-and-blues.org/weblog/…/et-de-la-presentation

The blog owner is a prominent web standards writer, so I hope some of you will be able to read it.

[ Gravatar Icon ]

Perishable#7

@Gabe: I see where you (and Louis) are coming from, and definitely agree that, in general, separation of PHP from (X)HTML is good practice. For this technique, the goal was to make the randomization of images as simple as possible. Personally, I find the devised method quite useful in its simplicity and elegance: a single line of code to display a series of random images is a good thing! ;)

@Johann: I appreciate the constructive criticism, however I feel as if you have missed the overall point of the article. As mentioned previously, the goal for this tutorial was a “drop-dead” simple method of displaying a series of random images. The result? A single line of code! Honestly, you can take the width, height, and alt attributes and manipulate them however you wish. That really wasn’t the point. I suppose that I am working from the assumption that my readers understand that they are free (and encouraged) to change and adapt the code to suit their needs. Nobody should feel obliged to use the code exactly as it is presented, especially if they know of a better way. In any case, thanks again for the feedback, I enjoyed responding to it :)

@Louis: Excellent points as usual! As I’ve said before, “I wish I spoke French!” ;)

[ Gravatar Icon ]

Louis#8

Jeff: too bad you can’t, it really is some deep discussion on the subject. I have never seen something equivalent on an english website.

About your response to Gabe & Johann, if the aim of this tutorial is to be to simplest as possible, then I think you could drop the variable, and use this shorter code.

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

[ Gravatar Icon ]

Perishable#9

Oh, that sucks — I always hate to miss an important conversation, especially such a deep one. Nonetheless, I think your simpler version of the randomizing code is indeed a significant improvement. Thanks for sharing! :)

[ Gravatar Icon ]

david#10

i am totally new to this guys, but i wanted to put some random images on my site, i followed this tutorial and can’t seem to get it to work. so frustrating! can someone please help?
hopeghost.com

[ Gravatar Icon ]

Perishable#11

Sure, david, happy to help. I have replied to your email and will try to figure things out from there.. :)

[ Gravatar Icon ]

Carlo#12

Being a newbie at php, I’d like to know if this code works for php3, because it doesn’t seem to be working on the page i’m working on. Yeah, sorry, it’s not my site. Just trying to help a friend.

[ Gravatar Icon ]

Jeff Starr#13

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

[ Gravatar Icon ]

Carlo#14

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.

[ Gravatar Icon ]

SneakyWho_am_i#15

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!

[ Gravatar Icon ]

Jeff Starr#16

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

[ Gravatar Icon ]

Leprakawn#17

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

Thanks!

[ Gravatar Icon ]

Radek#18

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?

[ Gravatar Icon ]

Jeff Starr#19

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

[ Gravatar Icon ]

Radek#20

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

[ Gravatar Icon ]

Jeff Starr#21

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

[ Gravatar Icon ]

Radek#22

I would but I am looking for one :)

[ Gravatar Icon ]

Jeff Starr#23

Have you tried Google?

“non-repeating random images php”

Yields many results..

[ Gravatar Icon ]

Josh#24

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?

[ Gravatar Icon ]

ESSA#25

Hi, this PHP code is great, it works fine, thank you very much :)

Although I have a question: would it be possible to only show 10 images (among the 30 images from the directory), changing randomly on page reload?

I tried to modify the script but since I’m not a PHP-coder, I didn’t succeeded. So I thought I could maybe ask for help here.

Thanks a lot!

[ Gravatar Icon ]

Tejedor#26

Excellent!! This is what I was looking for. Something very simple and usefull.

Thanks.

Comments are closed for this post

If you have or need further information, contact me.



Attention: Do NOT follow this link!