Question

Automatic Image Randomizer with CSS

Asked by: turtleman2009

I am using the  Automatic Image Rotator Script and it works fine except I am using the same css style several times on a page and I would like a different image to show up each time the style is used.

Any help would be greatly appreciated!

<?php
 
/*
 
	AUTOMATIC IMAGE ROTATOR
	Version 2.2 - December 4, 2003
	Copyright (c) 2002-2003 Dan P. Benjamin, Automatic, Ltd.
	All Rights Reserved.
 
	http://www.hiveware.com/imagerotator.php
	
	http://www.automaticlabs.com/
	
	
	DISCLAIMER
	Automatic, Ltd. makes no representations or warranties about
	the suitability of the software, either express or
	implied, including but not limited to the implied
	warranties of merchantability, fitness for a particular
	purpose, or non-infringement. Dan P. Benjamin and Automatic, Ltd.
	shall not be liable for any damages suffered by licensee
	as a result of using, modifying or distributing this
	software or its derivatives.
	
	
	ABOUT
	This PHP script will randomly select an image file from a
	folder of images on your webserver.  You can then link to it
	as you would any standard image file and you'll see a random
	image each time you reload.
	
	When you want to add or remove images from the rotation-pool,
	just add or remove them from the image rotation folder.
 
 
	VERSION CHANGES
	Version 1.0
		- Release version
	
	Version 1.5
		- Tweaked a few boring bugs
	
	Version 2.0
		- Complete rewrite from the ground-up
		- Made it clearer where to make modifications
		- Made it easier to specify/change the rotation-folder
		- Made it easier to specify/change supported image types
		- Wrote better instructions and info (you're them reading now)
		- Significant speed improvements
		- More error checking
		- Cleaner code (albeit more PHP-specific)
		- Better/faster random number generation and file-type parsing
		- Added a feature where the image to display can be specified
		- Added a cool feature where, if an error occurs (such as no
		  images being found in the specified folder) *and* you're
		  lucky enough to have the GD libraries compiled into PHP on
		  your webserver, we generate a replacement "error image" on
		  the fly.
		
    Version 2.1
        - Updated a potential security flaw when value-matching
          filenames
 
    Version 2.2
        - Updated a few more potential security issues
        - Optimized the code a bit.
        - Expanded the doc for adding new mime/image types.
 
        Thanks to faithful ALA reader Justin Greer for
        lots of good tips and solid code contribution!
 
 
	INSTRUCTIONS
	1. Modify the $folder setting in the configuration section below.
	2. Add image types if needed (most users can ignore that part).
	3. Upload this file (rotate.php) to your webserver.  I recommend
	   uploading it to the same folder as your images.
	4. Link to the file as you would any normal image file, like this:
 
			<img src="http://example.com/rotate.php">
 
	5. You can also specify the image to display like this:
 
			<img src="http://example.com/rotate.php?img=gorilla.jpg">
		
		This would specify that an image named "gorilla.jpg" located
		in the image-rotation folder should be displayed.
	
	That's it, you're done.
 
*/
 
 
 
 
/* ------------------------- CONFIGURATION -----------------------
 
 
	Set $folder to the full path to the location of your images.
	For example: $folder = '/user/me/example.com/images/';
	If the rotate.php file will be in the same folder as your
	images then you should leave it set to $folder = '.';
 
*/
 
 
	$folder = '.';
 
 
/*	
 
	Most users can safely ignore this part.  If you're a programmer,
	keep reading, if not, you're done.  Go get some coffee.
 
    If you'd like to enable additional image types other than
	gif, jpg, and png, add a duplicate line to the section below
	for the new image type.
	
	Add the new file-type, single-quoted, inside brackets.
	
	Add the mime-type to be sent to the browser, also single-quoted,
	after the equal sign.
	
	For example:
	
	PDF Files:
 
		$extList['pdf'] = 'application/pdf';
	
    CSS Files:
 
        $extList['css'] = 'text/css';
 
    You can even serve up random HTML files:
 
	    $extList['html'] = 'text/html';
	    $extList['htm'] = 'text/html';
 
    Just be sure your mime-type definition is correct!
 
*/
 
    $extList = array();
	$extList['gif'] = 'image/gif';
	$extList['jpg'] = 'image/jpeg';
	$extList['jpeg'] = 'image/jpeg';
	$extList['png'] = 'image/png';
	
 
// You don't need to edit anything after this point.
 
 
// --------------------- END CONFIGURATION -----------------------
 
$img = null;
 
if (substr($folder,-1) != '/') {
	$folder = $folder.'/';
}
 
if (isset($_GET['img'])) {
	$imageInfo = pathinfo($_GET['img']);
	if (
	    isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
        file_exists( $folder.$imageInfo['basename'] )
    ) {
		$img = $folder.$imageInfo['basename'];
	}
} else {
	$fileList = array();
	$handle = opendir($folder);
	while ( false !== ( $file = readdir($handle) ) ) {
		$file_info = pathinfo($file);
		if (
		    isset( $extList[ strtolower( $file_info['extension'] ) ] )
		) {
			$fileList[] = $file;
		}
	}
	closedir($handle);
 
	if (count($fileList) > 0) {
		$imageNumber = time() % count($fileList);
		$img = $folder.$fileList[$imageNumber];
	}
}
 
if ($img!=null) {
	$imageInfo = pathinfo($img);
	$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
	header ($contentType);
	readfile($img);
} else {
	if ( function_exists('imagecreate') ) {
		header ("Content-type: image/png");
		$im = @imagecreate (100, 100)
		    or die ("Cannot initialize new GD image stream");
		$background_color = imagecolorallocate ($im, 255, 255, 255);
		$text_color = imagecolorallocate ($im, 0,0,0);
		imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
		imagepng ($im);
		imagedestroy($im);
	}
}
 
?>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-18 at 23:43:31ID24663855
Topics

Dynamic HTML (DHTML)

,

PHP Scripting Language

Participating Experts
1
Points
500
Comments
6

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Losing image rotation in Netscrap 4.74 with CSS
    Please help a neophyte who's stuck. New to CSS and JavaScript I'm trying to absolutely position a rotating image. IE does it just fine; but Netscape won't rotate the image if I use CSS. Without any CSS the images rotate just fine in Netscape, but I need to place the image ...
  2. Random background images in CSS
    My page has an external style sheet attached which specifies a background image for my site: #midimage { height: 300px; width: 770px; margin: 0px; padding: 0px; float: left; background-image: url(../images/midimage1.jpg); } I want to be able to display a random image ...
  3. PHP Random Image Rotation
    Hi, I am using the script below to rotate four images on a page, unfortunately it always uses the same image for all 4 pictures. I need it to show a random image that is not repeated in the other four images. Is there a simple way to modify this script to serve this purpose?...
  4. CSS Image Rotate?
    is it possible to rotate an Image using CSS?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: fiboPosted on 2009-08-19 at 04:41:57ID: 25131483

Could you provide more details?

Are the images displaying one/ page or several / page?
If several, could you show the php code you use to generate the html?
You might consider that each image is displayed within a left-floating div with some css style: you might select randomly which style among several.

 

by: turtleman2009Posted on 2009-08-19 at 05:40:22ID: 25131907

I am actually using this on a wordpress blog. This is going to be the image that displays next to each post (in my case a butterfly). The blog is here: http://blog.adazing.com/wordpress/

So in my case each new post and there are multiple for each page uses this code:

<div class="post" id="post-<?php the_ID(); ?>">
            <h1><?php the_title(); ?></h1>
            <div class="entry">
                  <?php the_content(); ?>
            </div>

            <div class="postmetadata">
                  <?php df_get_postmetadata( array( "edit" ), 'span' ); ?>
            </div>
</div>

It is the class="post" style that uses the random background, I want there to be a different butterfly for each post.

I hope this clarify's what I would like to do.

 

by: fiboPosted on 2009-08-19 at 06:44:13ID: 25132494

OK. I had a look at the blog and its style.
From what I understand,
http://blog.adazing.com/wordpress/wp-content/themes/grass/rotate/rotate.php provides you with a different picture each time you are calling it.

This is what appears in the css file
http://blog.adazing.com/wordpress/wp-content/themes/grass/style.css

Problem is that rotate.php is just called once per page load (or reload), so it changes each time but is the same all over the page.

This leaves you with 2 options:
- leave things as they are, or ask the template author/vendor if there is some option to make it change images
- make changes so that instead of always using style '.post' it uses sometimes 'post-1', sometimes 'post-2' etc.

For this option to work, assuming we want 4 "different" (read: somehow random) styles:
- change at line 91 in style.css (changes would probably work for any number of images, maybe up to 9)
      .post {
to
      .post-1, post-2, post-3, post-4,
                .post {

and just before  .post hr{
add
.post-1 {background-image: url(rotate/rotate.php)}
.post-2 {background-image: url(rotate/rotate.php)}
.post-3 {background-image: url(rotate/rotate.php)}
.post-4 {background-image: url(rotate/rotate.php)}

And now change
<div class="post" id="post-<?php the_ID(); ?>">
to
<div class="post-<?php echo rand(1,4) ?>" id="post-<?php the_ID(); ?>">

Although the styles for post-1 etc look "the same", they will (or more precisely should) return different results (which does not mean that sometimes they would not be the same; for instance here since we have 3 images, at least 2 of the 4 will be the same "this time", but "next time" these values would change")
Since I have no info on "rotate.php" though, I am not sure what it does exactly: is it limited to 3 different images? is there any constraint on their name except being jpg?
If you do not have this info, you should probably test that first:
- add in http://blog.adazing.com/wordpress//wp-content/themes/grass/rotate/ several other images with different names (do not care for dimensions at this stage).
- repeatedly update page http://blog.adazing.com/wordpress//wp-content/themes/grass/rotate/rotate.php
do you get the new pictures? or never, even if you have made 10-15 updates?
- if you get the new pictures: presumably you can use any number of pictures of any name (but remember that at some stage dimensions might be important!), because apparently the program looks at all the jpg files in the directory
- if you get only the 3 previous images: names are somehow hard-coded.... first rename 3 of your new files as "butterpost4.jpg" ...5... ...6... and update the page. are you still getting the 3 previous, or are you also seeing the new pictures?
- if you can see the new, presumably you should be able to get also 7 8 and 9. Maybe more: test to know.
- If you are still stuck with the 3... bad luck, the program is hard-coded, and you will be limited to the 3 pictures (but you are still able to have several different on the same page.

NOTES:
You might alternatively  use some javascript to, once the page is loaded, directly attack the DOM code and the style of each ".post" div, since they have a different ID: you might/ change replace the background of the div with a one provided by rotate.php, ie random at each time. This would need NO other change to css or php.
If you implement it, remember that you must call rotate.php for each div

 

by: turtleman2009Posted on 2009-08-19 at 06:51:30ID: 25132575

the source of the rotate.php file is attatched at the top with my original question

 

by: fiboPosted on 2009-08-19 at 09:55:24ID: 25134810

B-)) I had forgotten this source!

Looking at it answers the question: it is using all images files present in the directory, and uses them 'as is'.

 

by: fiboPosted on 2009-08-19 at 11:46:39ID: 25135887

Since your code already uses JQuery, this would allow you to "easily" change the backgroun image individually for each div of class post... but I am not fluent enough in JQuery to be helpful.

Note that you should probably not use "the smart way" which would allow you to change all these at once: it would call rotate.php just once, so all the pictures would be the same!

What I had in mind was to explore the effect of adding, close to the end of the <body> a piece of code edited from
<script>
$(document).ready(function() {
    $(div[class=post]).each(function(i) {
          this.backgroundImage='url(rotate/rotate.php)';
    } );
})
</script>

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...