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!)..
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! ;)
26 responses to “Drop-Dead Easy Random Images via PHP”
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 :)
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, please wrap single-line snippets in
<code>
tags, and multiple-line snippets in both pre and code tags:<pre>
<code>
.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!
I’m afraid I don’t like your approach that much. First
height="50"
andwidth="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.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.
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.
@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
, andalt
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!” ;)
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" />
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! :)
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
Sure, david, happy to help. I have replied to your email and will try to figure things out from there.. :)
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.