Display random image from directory
I'm very proud of this little baby because it's the first script I created 100% on my own. It isn't much and I'm sure there are much better ways to do it, but it's my baby.
This script will allow you to display images in a set directory randomly. To see this script in action, click here and reload, reload, reload.
There is at least one caveat that I know about - images must exist in one directory with no sub directories. Theoretically, this shouldn't be a problem, but I've had problems with the script when trying to run it in a directory with subdirectories.
So what will you need?
a) PHP The page you display this script on must have a php extension and your server should be able to read PHP. It's a lifeblood. Get used to it.
b) a directory of images residing on your server Most people organize their site enough that their images are already in a directory by their lonesome. You can also pull only certain extensions or endings, as will be described later. But for example, if you name all your thumbnails: image-thumb.jpg you can pull all your thumbnails up randomly.
And enough of my babble, here's the meat of the script. Pay attention to anything red for later:
<?
# Put the SERVER PATH to image directory.
# INCLUDE trailing slash
$dir = "/home/username/public_html/pathto/yourphotos/";
# Put the HTML PATH to image directory.
# DO NOT include trailing slash
$html_dir = "http://www.yoursite.com/pathto/yourphotos";
$dir_handle = opendir($dir);
$image_array = array();
# This opens up the image directory, grabs all files with a ".jpg" extension
# and puts them into an array. You can set whatever extension you'd like here.
# Just switch out the .jpg for .gif, etc. If you have more than one extension,
# replace this line with something like this:
# if (($file !=".") && ($file !="..") && (substr($file, -4) == ".jpg") || (substr($file, -4) == ".gif"))) {
# This will pull up all .jpg OR .gifs. If you name all the images you want to pull
# a certain way (example, image-thumb.jpg or image.thumb.jpg) you can do this:
# if (($file !=".") && ($file !="..") && (substr($file, -10) == ".thumb.jpg")) {
# basically you want to put the extension in quotes and then count how many characters
# it is and place that after $file, -
while ($file = readdir($dir_handle)) {
if (($file !=".") && ($file !="..") && (substr($file, -4) == ".jpg")) {
$file_name = "$html_dir/$file";
$image_array[$file_name] = $file_name;
}
}
# sorts the array. For some reason this won't work at all
# unless this is done. Can anyone tell me why?
sort($image_array);
$count = sizeof($image_array);
# trims all the URLs of whitespace and assigns each
# item in the array a number to identify it.
for($i = 0;$i<sizeof($image_array); $i++) {
$image[$j++] = rtrim($image_array[$i]);
}
# assign a random value
$r = rand(0,$count-1);
# get the size of a random image
$size = getimagesize($image[$r]);
$width = $size[0];
$height = $size[1];
# This is the HTML output. You can change any of this, but you should
# leave src=\"$image[$r]\" width=\"$width\" height=\"$height\" where it is.
# Remember to escape any quotation marks, etc.
$img_src = "<img src=\"$image[$r]\" width=\"$width\" height=\"$height\" alt=\"This is a Random Image\" />";
# closes the directory (why keep it open?)
closedir ($dir_handle);
?>
Okay, pretty straight forward. You want to replace the first two red things with the SERVER path to your image directory and the HTML path to your image directory, respectively. Use the example as a guide.
The third colored thing, the BLUE one, you'll only need to pay attention to if you want to add extensions or specify end-of-file-names, such as image-thumb.jpg. So I'll skip that and come back to it in a minute.
You want to place this code near the top of your HTML document. I usually place stuff like this right below the BODY tag to make sure it's above the place you're actually going to call the image.
Then, wherever you want to place the random image, place this code:
<? echo $img_src; ?>
Simple, no? ![]()
Okay, and the last little bit. Say you have all your thumbnails named image.thumbnail.jpg The .thumb.jpg never changes so you can tell the script to call up .thumb.jpg and ONLY display THOSE images.
To do that, you'd replace the above BLUE code with the following (exactly, character for character or you'll get a parse error):
(substr($file, -10) == ".thumb.jpg")
Here's how that works. the "-10" above is how many characters from the end the script should count. the text inside the quotes, .thumb.jpg is 10 characters and you're telling the script that's what should appear.
You can do a variety of things with this. If you wanted to pull up all .jpg AND all .gif files, you'd replace the BLUE text above with the following:
((substr($file, -4) == ".jpg") || (substr($file, -4) == ".gif"))
If you wanted to EXCLUDE all thumbnails using the above example, you'd place the following:
(substr($file, -10) != ".thumb.jpg")
It goes on and on.
—
Again, as this is the first (lengthy) script I've done completely on my own, there may be bugs and I may have done something the hard way. I appreciate any comments with quirks, questions or suggestions for a more effecient way to do this.
April 22nd, 2002 at 7:50 pm
Wheeeeee! That was fun!
I'm very impressed that you wrote the whole script. Way to go! I may be trying this out in the next month or so!
April 22nd, 2002 at 9:13 pm
You can get php to figure out the dimensions of a picture?!? That would be so handy.
I'm using a fully written out array for mine. And I have three random images at once, called from different parts of the array.
I might have a play with this script. Thanks for sharing it!
April 22nd, 2002 at 9:17 pm
Ohh, I'd want to have different alt text for my images
So maybe I have to stick with what I'm doing already.
April 22nd, 2002 at 10:08 pm
That is excellent!!! What are you talking about "you don't know PHP that well"… DAMN!!
Question for you - what are you using for references? Just curious… are you just using http://www.php.net, or are your using any particular books?
April 22nd, 2002 at 10:26 pm
I've been using getimagesize for a while now because I got SO tired of trying to figure out image sizes for each individual file.
If you wanted to set something up to automatically figure out the image height/width and print out an image tag, I think this woud work.
Place the following at the top of your HTML files (again, right under BODY is a good place):
<?
function image($file, $alt) {
$size = getimagesize($file);
$width = $size[0];
$height = $size[1];
print "<img src=\"$file\" width=\"$width\" height=\"$height\" alt=\"$alt\" border=\"0\" />";
}
?>
This creates a function so all you need to do is specify the function and point it to the URL of the file and give it the alt text and it will write out the whole bit of code for you. For some it might be more trouble than it's worth, but for people who put up a LOT of images on their site, if you don't automatically know the width/height it can be a huge time saver.
With that bit of code at the top of your page, you can call up the following anywhere below that:
<? image("http://www.yoursite.com/path/to/image.jpg", "Here is the alt text"); ?>
Obviously in the first set of parenthesis goes the URL to the image (I think full URL or SERVER path is all that will work here) and in the second set goes the alt text. If you want to leave it blank, just put "" instead of putting text.
I need to learn more about creating functions in PHP. Fun stuff.
April 22nd, 2002 at 10:29 pm
Jennifer - today for this script, I just used php.net - wow, what a tool!!! In the past few days I've really learned how to utilize it to find what I need.
I also have the book Beginning PHP4 which I haven't been able to read through but has been a good resource from time to time.
I think I'm liking php.net more though.
April 23rd, 2002 at 5:29 am
Hey, thanks for that Lynda!
April 23rd, 2002 at 7:45 am
Wow! I really can use the code snippet for sizing. I knew php could do this, but an example really helps.
April 26th, 2002 at 11:20 am
Oh this is WONDERFUL!! I've been looking for a script just like this. Thank you
May 15th, 2002 at 9:34 am
Nice and it works, too! But I wish there was an option to only use one image per day, instead of throwing up a new one every time the browser refreshes. I'm using it as a "pic of the day" feature, but as it is now, it's more like "pic per click!"
May 16th, 2002 at 11:33 am
If you've tons of static html pages, you can make a PHP script that outputs a javascript which can be called from static html to do this.
Here's how I implemented this to put rotating banners and photographs -
http://vsbabu.org/banners/howto.html
Instead of files in a folder, it looks into an XML file - so additional attributes can be had too.
June 3rd, 2002 at 11:45 pm
Hey there Scriptygoddesses! I've been trying to get this to work, but I'm obviously doing something wrong. All my error messages are centering around the part of the code pertaining to getting the size of the random image. You can see the error message here: http://www.planetgaile.com/random.php
This is the line referred to: $size = getimagesize($image[$r]);
Help? Thanks!
July 5th, 2002 at 9:48 pm
i'm having trouble getting this to work too. there is some code that shows up at the top of the page:
"; # closes the directory (why keep it open?) closedir ($dir_handle); ?>
You can see it here:
http://www.elcajonfire.com/main-css.php
The pic is supposed to show up under "Photo Op" on the right sidebar.
Thanks for any help you can give me!
July 6th, 2002 at 12:02 am
well never mind. i removed the code because i thought it was causing a problem in NS7. turns out the problem is still there. i'll put it back when i figure this out.
July 12th, 2002 at 6:03 am
This was awesome - worked like a charm! Thank you!
July 25th, 2002 at 10:50 pm
Just found your site - and just in time, too! I'm just learning PHP, so it's nice to find a well done site like yours at this point in the learning process. So, is it just me, or do women actually understand the value of DOCUMENTING CODE better? I can't tell you how much I appreciate well-documented code (like yours) especially when applied to such elegant solutions. Thanks for all your hard work!
September 30th, 2002 at 12:51 pm
Automatic Image Dimensions and Scaling:
Here's a function that I use on my site, if I don't know the image size, but want to restrict it to a certain width (which in most layouts is more critical than image height). The function keeps the correct aspect ratio so the image doesn't look distorted.
function display_image($imgurl) {
$maxwidth =100;
$imagehw =@GetImageSize($imgurl);
$imagewidth =$imagehw[0];
$imageheight =$imagehw[1];
if ($imagewidth>$maxwidth) {
$imageprop =($maxwidth*100)/$imagewidth;
$imagevsize =($imageheight*$imageprop)/100;
$imagewidth =$maxwidth;
$imageheight =ceil($imagevsize);
}
echo '<img src="'.$imgurl.'" width='.$imagewidth.' height='.$imageheight.'>';
}
You can change the function easily by making maxwidth a parameter, or for example, the alt-text. I hope someone will find this useful
October 13th, 2002 at 2:52 am
Hey Jennifer,
This is just the fantastic script I was searching for, thank you! Just one question, how can I assign a static URL to the photos? I'd like to display one random image from each of my photo sets on an index page, so people can click it and be directed to a full thumnail page.
Again thank you!
October 14th, 2002 at 6:43 am
I came upon this script and thought it may be of use to people searching for random image php scripts:
<?
$path = "http://path.to.images/with.trailing.slash/";
$imgcount = rand (0,1);
$imgcounttag = "<img src=\"$path$imgcount.jpg\" ALT=\"\" BORDER=\"0\"> ";
echo $imgcounttag;
?>
Just remember your pictures in the folder must be named 0.jpg up to whatever-number.jpg - those are the rand (0,7) numbers above.
You can also add image height and width tags like so:
WIDTH=\"166\" HEIGHT=\"247\"
October 14th, 2002 at 6:44 am
There is also a great script (php) for randomizing text or images over here:
http://studioid.com/projects/php/randomizer.php
December 17th, 2002 at 4:10 pm
I am truly blessed, cuz I not only got the $size = getimagesize($image[$r]); error but also the "; # closes the directory (why keep it open?) closedir ($dir_handle); ?>
whooopee!
January 13th, 2003 at 9:30 pm
I've been struggling with this script this evening. To test I have uploaded 3 images into one directory. Because of that small number it was easy for me to see only *two* of the three images were displayed. The first image would never appear. Doing a lot of ECHO tracing I saw that the script *does* read all the images but one gets lost in the part where a number is assigned to each $image[#].
Trying some more I found that adding a
$j = 0
before that routine helped.
Before:
# trims all the URLs of whitespace and assigns each
# item in the array a number to identify it.
for($i = 0;$i<sizeof($image_array); $i++) {
$image[$j++] = rtrim($image_array[$i]);
}
After:
# trims all the URLs of whitespace and assigns each
# item in the array a number to identify it.
$j = 0;
for($i = 0;$i<sizeof($image_array); $i++) {
$image[$j++] = rtrim($image_array[$i]);
}
I'm kind of happy with myself as I copy-&-pasting and editing my way to some PHP understanding.
January 17th, 2003 at 7:43 am
you have to replace
# trims all the URLs of whitespace and assigns each
# item in the array a number to identify it.
for($i = 0;$i
February 11th, 2003 at 3:01 am
Hi, first of all these scripts are just what I 've been looking for! I currently am employing a super basic php random image generator:
<?php $rand = rand(0,143); ?>
<img src="directory/<?php echo rand(1,144) ?>.jpg">
but the problem with this is it breaks css layers in certain browsers because of the unknown image size.
I've tried both scripts on this page with the getimagesize command and i'm getting errors. I don't know much php… just cut and paste stuff, but your site is a great resource!
one page in question using the top script is http://onesolidgear/another.php
thank you.
April 29th, 2003 at 12:29 am
Great script. It does what it says it will do perfectly. I'm going to work on adding something to it for myself. Maybe you can help so I don't have to burn to many cycles. I have photos in multiple sub directorys off of one URL/photo directory. i.e.
photo
.Son
..image.jpg
..tn
…thumb.image.jpg
.Me
.Cars
.Stuff
In these directories I have a tn/ direcory with the thumbnails for the pictures in the subdirectories.
If I configure your script to look in the photo/sub/tn directory it works perfect, but for that directory only. What I was thinking would be neat would be to get a list of the subdirectories under /photo/ then pic one and run your script on the /photo/randomsub/tn directory. Probably not that hard. In fact after typing this I think I know how to do it.. email me if you have an idea though.. thanks, and great script!
May 1st, 2003 at 9:15 pm
To Gaile,
Regards to your error.
The line should start with the # (to prevent it from being run by PHP)
So it should look like.
# closes the directory (why keep it open?) closedir ($dir_handle); ?>
NOT
"; # closes the directory (why keep it open?) closedir ($dir_handle); ?>
As the "; is closing the the pervious line.
You may want to watch out for this especially when you copy and past code into a SSH window and it wraps text onto the next line.
May 4th, 2003 at 2:45 am
I tried the one at phpprincess net but it didn't work for me. This one does
May 14th, 2003 at 3:04 am
im a php newb, but this looks simple enough
about to test it out. it's nice to have side notes on what everything does thnx for the script 
May 14th, 2003 at 1:29 pm
hrm im having a bit of trouble excluding thumbnail files, its giving me a parse error. can someone give me an example of what the 'if' line would look like
thnx in advance
May 14th, 2003 at 3:12 pm
Umm could I use this script with width and height limitations? Like you know when you join a forum and the specify the avatar can only be up to X and width=x…etc
can that be done with this script?
May 14th, 2003 at 5:33 pm
bleh my other post didnt come up, said iwas reading code wrong ;p so i got it to work,
but i was also wondering can php do something like make a page popup with restricted height and width using the code here?
some thing like
a href="javascript:window.open('http://url' width='x' height='y')
could the above script be used to auto snap the popup to the image size? if not could php do window popups somewhat similar to what i just posted?
June 4th, 2003 at 2:25 pm
I've been sitting here staring at this code for hours trying to get it to work on the new site that I'm building. But, this being the first PHP code I've ever used…I'm quite confused.
I can handle copy and paste, but the problem is…I don't know what part of the code I need to customize for myself. What should I leave standard and what do I need to change?
Hopefully you can help me shed some light on this.
June 27th, 2003 at 1:08 am
To Gaile & Scott,
Regards to the error.
I think something missed in your responce Scott, which I also did at first, is that the file extension should be .php (or whatever your server likes).. When it's a .html it gave me the exact same error.. Just rename your file and it should fix that…
Cheers
August 27th, 2003 at 10:40 am
I get the error that someone else above also noticed"
"; # closes the directory (why keep it open?) closedir ($dir_handle); ?>
I think it has something to so with the img_src line where it assigns the string…
Any idea what is happenening to me?
http://www.firebreathingdragons.com
Thanks!
August 27th, 2003 at 11:06 am
If you look at your source code, it's actually showing ALL the code that should be processed by the server (ie. NOTHING between <? ?> should ever show up on your browser page or when you view source. It could be a million things - but the first question I'd start with are you sure php is working on your site? (ie, if you set up a page that has nothing but <? phpinfo(); ?> on it, what happens? If the answer is nothing… php isn't running…
August 27th, 2003 at 2:01 pm
Thanks Jennifer,
Php works fine - I have a gallery photo thing working great and phpinfo() returns all the regular stuff.
I think that the "/>" part of the img_src line is causing the php parser to think it's the end of the script. Any ideas for a solution????
Thanks
Kynan
August 27th, 2003 at 2:33 pm
The problem is occuring even earlier than that… as I said before - if you view source, ALL the php code is displaying… my next guess would be to see what's happening with your line breaks - make sure you haven't inadvertently commented out more code than you expcted too (maybe try removing all the comments to be sure…?) The page you're working with looks like some kind of apache test page - is that what you trying to change?
August 27th, 2003 at 3:32 pm
You are right, php must not be working for that page:
http://www.firebreathingdragons.com/phpinfo.php
gives nothing…
But why?
http://www.firebreathingdragons.com/gallery
and
http://www.firebreathingdragons.com/gallery/setup/phpinfo.php
works fine. So php is running, just not for my main directory?
Is this something I have to delve into php.ini for?
Thanks,
Kynan
August 27th, 2003 at 3:36 pm
Oh Oh Oh I think I got it.
My version of php seems to require:
<?php stuff ?>
Going to fine tune it all now…
Thanks for your help Jennifer!
Great site(s) by the way!
August 27th, 2003 at 3:55 pm
Unfortunately server configurations is not my specialty… :-\ Good luck!!
September 23rd, 2003 at 10:02 pm
Thanks you so much! Ive been looking for something like this for a long time. And now i come across yours which is nice and simple even i made it work!
November 27th, 2003 at 10:24 am
I have adjusted the script using some suggestions from here. I am using it within a block module on the current version of phpwebsite with great success.. Thanks for your efforts..
Here are the details:
Save the script as randimg.php.. I have discovered iframes which seem to do the trick.. Add the iframe tag to the textsettings.php file in conf dir of phpwebsite. Add the following to the block content:
<iframe marginwidth="0" marginheight="0" width="180" scrolling="no" frameborder=0 src="randimg.php"></iframe>
Rob
<?php
# Put the SERVER PATH to image directory.
# INCLUDE trailing slash
$dir = "/home/user/html/images/photoalbum/1/";
# Put the HTML PATH to image directory.
# DO NOT include trailing slash
$html_dir = "http://www.someplace.com/images/photoalbum/1";
$dir_handle = opendir($dir);
$image_array = array();
# This opens up the image directory, grabs all files with a ".jpg" extension
# and puts them into an array. You can set whatever extension you'd like here.
# Just switch out the .jpg for .gif, etc. If you have more than one extension,
# replace this line with something like this:
# if (($file !=".") && ($file !="..") && (substr($file, -4) == ".jpg") || (substr($file, -4) == ".gif"))) {
# This will pull up all .jpg OR .gifs. If you name all the images you want to pull
# a certain way (example, image-thumb.jpg or image.thumb.jpg) you can do this:
# if (($file !=".") && ($file !="..") && (substr($file, -10) == ".thumb.jpg")) {
# basically you want to put the extension in quotes and then count how many characters
# it is and place that after $file, -
while ($file = readdir($dir_handle)) {
if (($file !=".") && ($file !="..") && (substr($file, -6) == "tn.jpg")) {
$file_name = "$html_dir/$file";
$image_array[$file_name] = $file_name;
}
}
# sorts the array. For some reason this won't work at all
# unless this is done. Can anyone tell me why?
sort($image_array);
$count = sizeof($image_array);
# trims all the URLs of whitespace and assigns each
# item in the array a number to identify it.
for($i = 0;$i<$count; $i++) {
$image[$i] = rtrim($image_array[$i]);
}
# assign a random value
$r = rand(0,$count-1);
# get the size of a random image
$size = getimagesize($image[$r]);
$width = $size[0];
$height = $size[1];
# This is the HTML output. You can change any of this, but you should
# leave src=\"$image[$r]\" width=\"$width\" height=\"$height\" where it is.
# Remember to escape any quotation marks, etc.
$img_src = "<center><img src=\"$image[$r]\" width=\"$width\" height=\"$height\" alt=\"This is a Random Image\" /></center>";
echo $img_src;
# closes the directory (why keep it open?)
closedir ($dir_handle);
?>
December 18th, 2003 at 3:11 am
Does this not work if u have sub directories in your images fold e.g.
images > example
> example 2
and each sub fold has images in them . This is annoying me as i have different sub folders in my main images folder and this script doesn't work !
December 18th, 2003 at 6:53 am
Sorry - no, it doesn't support sub directories. I'm sure there IS a way to do that in PHP, but this particular script does not do that…
December 18th, 2003 at 6:54 am
Or actually more specifically - as she said above in the post:
There is at least one caveat that I know about - images must exist in one directory with no sub directories. Theoretically, this shouldn't be a problem, but I've had problems with the script when trying to run it in a directory with subdirectories.
March 21st, 2004 at 12:48 pm
Your random image code seems to pull the same images a lot of the time.
April 21st, 2004 at 11:59 am
The following code has come in handy for me, and is a bit more effecient than the original code. Adjust it with any of the extra bells and whistles as needed.
# Relative to current directory
$imgdir = 'random/image/directory/';
$dir = $_SERVER['DOCUMENT_ROOT'] . '/' . $imgdir;
$images = array();
#
# The user doesn't need to see any errors
$dir_handle = @opendir($dir);
#
# The correct way to iterate over a directory
# (see http://www.php.net/manual/en/function.readdir.php)
while (false !== ($file = readdir($dir_handle)))
if (!is_dir($file))
$images[] = "$file";
#
closedir ($dir_handle);
#
# The following appears to make things "more" random
srand((double)microtime()*1000000);
$r = rand(0,sizeof($images)-1);
#
echo "<img src=\"{$imgdir}{$images[$r]}\">";
December 29th, 2004 at 12:51 am
Any improvements about the sub-directories issue since you wrote this script? I own a gallery and all my images reside in folders (categories) and subfolders (subcategories). I badly need a script that picks a random image after checking all the folders and picks a random image. I know the logic but can't apply it.
- Create a (super)array
- Let the script browse the directories and add the image names to this array.
- Pick randomly from the array.
How?
March 22nd, 2005 at 8:28 pm
Love the script and im sure i can use it in many applications, I was wondering however if it was possibel to filter the display to show only images beginning with the word "thumb_" much like you have done with the
# if (($file !=".") && ($file !="..") && (substr($file, -10) == ".thumb.jpg"))
I use a coppermine gallery inside a ezcontents portal and displaying images on different pages with Coppermine is a bit of a task. (coppermine prefixes to identify thumbs) Your script would ideally suit me if it could filter accordingly.
regards