CSS Random Background Image Rotation
Published by Lafinboy May 26th, 2006 in CSS, PHPEdit: If you do not have access to the PHP source code on your site, try this random background image script generator
Here's something I've been playing with lately to add a little bit of visual dynamic interest to sites that don't have frequently changing content. The concept is not new - use image rotation to display random images on each page load. No great problem there, simply use a server-side script to select a random image. But what if your images are not content, are purely presentational, and are (read 'should be') background images?
Using [tag]PHP[/tag] to retrieve a random image from a folder, we can generate dynamic [tag]CSS [/tag] declarations through the page headers. This means we can change background images randomly on page load, and we can control which images are available by adding or removing them from the images folder.
First up we need to create the PHP script that will get the images from a folder, select a single image at random, and write the CSS declaration to the page header. Everything you need is in the following scripts, and all that needs customising is the path to your style and image folders. Copy and save this file as dynamic_css.php.
http://www.thought-after.com/2006/05/26/css-random-background-image-rotation/
This file will display a random background image to any element
targetted through a CSS id.
1) Place this file in the same location as your sites main stylesheet file.
2) In the head section of each page place the following @import statement.
<style type="text/css"> @import url(/path/to/dynamic_css.php) NOTE: the import must occur after all other style sheet links, imports and
declarations to avoid this dynamic style being over-written.
3) Create a folder to hold the images to be used for the random backgrounds.
4) Assign values to the following variables to complete the setup
$imgFolder - the path from the sites root to the image folder created at 3 above
example: $imgFolder = "/images/random-images/";
$element : the css ID of the element to apply the background image to
example: $element = "header";
5) That's it!!
***/
// Set up
$imgFolder = "/images/random-images/"; // the path from the sites root to the image folder created at 3 above
$element = "header"; // the css ID of the element to apply the background image to
// That's it!! Nothing below this line needs to be changed
$img = null;
// build up the path to the image folder
if (substr($imgFolder,0,1) != '/') {
$imgFolder = '/'.$imgFolder;
}
if (substr($imgFolder,-1) != '/') {
$imgFolder = $imgFolder.'/';
}
$path = $_SERVER['DOCUMENT_ROOT'] . $imgFolder;
// populate an array to hold valid file type extensions
$extList = array('gif','jpg','jpeg','png');
// create an array to hold the list of image files
$fileList = array();
// open a handle to the directory
$handle = opendir($path);
// loop through the contents of the directory
while ( false !== ( $file = readdir($handle) ) ) {
// get the info for each file
$file_info = pathinfo($file);
// check that the file in in the allowed extensions array
if ( in_array( strtolower( $file_info['extension'] ), $extList) ) {
// add the file to the array
$fileList[] = $file;
}
}
// close the handle to the directory
closedir($handle);
// if we have at least 1 file in the list
if (count($fileList) > 0) {
// select a random index from the file list array
$imageNumber = time() % count($fileList);
// assign the filename for that array index to the $img var
$img = $imgFolder . $fileList[$imageNumber];
$css = "#$element { background-image: url('".$img."'); }\n";
// tell the browser what we're sending
header('Content-type: text/css');
// and write out the css
echo $css;
}
?>
Now in the head of our HTML page import the dynamic css:
If you have set up your path correctly, which I'll admit always catches me out, then each page load should see a random background image displayed in the element specified in the dynamic CSS.
Obviously this method can be extended and modified to suit you exact circumstances. I currently pass page identifiers through the import statement as part of a querystring which then query a database for specific content, meaning I can specify a range of images for use on each page, and on each element on that page. The possibilities are seemingly endless, and only limited by your imagination.
Edit (16/07/2007): I've tidied the script up a little to make it easier to implement. Just a couple of documented steps to follow, and thats' it!!
81 Responses to “CSS Random Background Image Rotation”
- 1 Pingback on Dec 4th, 2007 at 2:56 pm
Hi
Thanks for the great tip and the code. I have one question in regards to the lien
$css = “#header { background-image: url(’”.$img.“‘); }\n“;
In my code editor this line does not seem to be reading correctly. An other words it is indicating that there is a syntax error somewhere. Also is it correct that you end with [ “ ] and not [” ] . this btw did not fix the syntax either.
Can you please get back to me please on this .
Thanks
Faruk
Faruk, the error has been fixed and the code updated. WP fancy quotes have been removed from the code blocks.
Is it possible for me to take that code and to change it? I'm searching for a solution for a website i'm thinking of.
For each visit on that webpage I would like the Background Color, the Typo color and 1 image to change… The rest of the content would not change.
For example i'd like to create let's say 10 different kind of color theme for my website, but for each visit the color is decided randomly. So i would have to load the CSS randomly but i dont know how to do it. Here I have found an example of something similar but i dont know PHP at all.
Is there a website that could help me do this?
Hey Joe
This script could certainly be modified to suit your requirements, but there is a much more complete and suitable solution that can be found in the article Generating dynamic CSS with PHP.
Good luck with modifying it to suit your requirements.
Hi! I'm a total noob to css. I want to use this code for my myspace page but I don't understand where to put the url's for my images. I don't know if I have the software to save a php file or how to do it- do I have to or can I put the code right in?
Also, can you customize the quantity of available images?
Thanks!
Hi notsirk
I don't use myspace, so can't be 100% certain, but am 99.99% sure that you would be unable to use any server side scripts such as PHP. That said, a quick Google for "myspace random background" brought up a service by Myspace-Plus which may be of use to you.
Hi
I have tried implementing the script, but it will not work for me.
Do you have an example of this script working anywhere so I can see what I have done wrong?
Thanks
David
Hi David
From a quick look at your site it would appear that you/your host does not have PHP directory listings enabled. If you have access, you can look in the php.ini file and check whether safe_mode_include_dir is set to ON. Note that this will only work when the safe_mode setting is set to ON as well.
Hi Lafinboy,
as you can see on my website, I have a javascript for changing my header image.
Now I was thinking of changing it a bit so it would be possible for the user to choose the image they want to see (with css).
No that I have seen your php-script, it seems to me that php will be better/easier to get this done.
Do you have any experience with that?
Hey Bram,
I guess you mean you want to have a little button/link on the image which, when clicked, will select another background image. For this level of response, while PHP could handle the server side generation/selection of the image, you would need to use Javascript, possibly an AJAX method, to call and replace the image. The above script will load a new image on each page load. The only way to have the image replaced without reloading the page would be to use client side scripting.
Hello Sir,
Thank you very much for this bit of php. This is a great bit of information.
However, I am having a bit of trouble implementing it on my site.
Here is the rundown:
I am being hosted by a company that offers a choice of SQL database. I chose a "pre-made" website database that acts as a photo album. I created the site so that my friends from "the old days" can browse pictures of our yesteryear and comment on the photos.
The "pre cast" website is made up of templates, one of which is style.css
Below is the body section of style.css
————————–
body {
background: white url(http://www.the-common.org/backgrounds/BGJungleJuice1.jpg) no-repeat fixed;
color: #000000;
font-family: Arial, Book Antiqua, Tahoma, Impact;
font-size: 12px;
/* this attribute sets the basis for all the other scrollbar colors (Internet Explorer 5.5 only) */
SCROLLBAR-BASE-color: #004c75;
SCROLLBAR-ARROW-color: #fcdc43;
}
————————–
I have tried to replace the background: url line with your:
@import url….
I have tested my paths to make sure they are correct.
Still I get a blank background.
My overall question then is, does the php code you supplied above tailor precisely to my situation when dealing with pre-cast templates like these?
I have played with the php some. If I visit the dynamic_css.php file that I have now a notepad document opens with the text:
background: white url(http://www.the-common.org/backgrounds/BGJungleJuice1.jpg) no-repeat fixed;
Each time I visit the php file the jpg file changes.
(It IS working :))
How can I get the text that opens in the notepad file to import into the proper line in my style.css template?
Any help is greatly appreciated!
Hi John - the @import directive (including opening and closing style tags) needs to be placed in the
section of the page, after the links to the stylesheets. This way the dynamic_css file style declarations will overwrite any previous declarations in the standard stylesheets.
i followed up on the advice about myspace plus- they have a solution that would be most do-able, but i was reading this and became interested in something- they have you upload your images to their site and apparently generate a random image program that can be used in myspace in many ways, but transmitted via their site. my question is how does it work? i wanted to have a table in my div layout that brought up a random image and an associated link with said image(the image owners profile and "add to" links, specifically) and i realize its retarded myspace, but its good learning experience. ive tried the random background codes and it usually doesnt show up (i use a real basic div layout but am still learning the basics- any slight change can mess up the layout and im not knowledgeable enough to fix some issues with that yet).
ok this sounds really complicated for what i am certain is a simple question. what kind of code can be made to bring up alternating states such as that? what do the "myspace generator" sites do exactly once you upload your images to them? i have the codes, but they say stuff like
and this was 4 different images- but only one url for all 4… but this does make a random background everytime you load the page…
(in fact, if you load that url above into your browser window you can see what it does when you refresh the page.) what is in this code that makes the code work? how does it know what 4 images i chose with only one url?
lol wow what a lot of stuff to ask. sorry, im still learning…
–body{background: url(http://www.mywackospace.com/images/random-images/17902) fixed}–
sorry this was the code from my previous post, i forgot to remnove elements, so it didnt show!
Hi, a really useful tutorial, but how do I configure it to put a random image into a table cell, not set it as a background? i'd imagine its simmilar but not to sure.
thanks
on Nov 2nd, 2 006 at 5:59 pm Lafinboy wrote:
"Hi David
From a quick look at your site it would appear that you/your host does not have PHP directory listings enabled. If you have access, you can look in the php.ini file and check whether safe_mode_include_dir is set to ON. Note that this will only work when the safe_mode setting is set to ON as well."
–
I actually just tested this script before reading your comment saying that your php server setting should be as follows in order for this script to work.
safe_mode = ON
safe_mode_include_dir = ON
..But I found this script to work even when setting were as follows.
So perhaps you might want to be sure to debug the code before you start modifying your server settings.~
If any of you are having problems debugging this code, you might to read your "Error Console" under the "Tools" menu in Firefox to see the errors. OR try viewing your script file in the browser directly be going to where it lives, i.e. http://www.example.com/dynamix_css.php and seeing what errors you find. If the script is working you should see the following in your browser:
#header { background-image: url('images/bkg3.jpg'); }
AND you will note that the background image is changing *each* time you hit refresh.
One last note, understand that this script is only specifying the background image for your id #header style. if you want it to change the entire page background just change "#header" to "body" in the code above.
I am unable to get it to work; except that the current bg image gets removed, not replaced! the import does not seem to write the new css. Gives a blank file. appreciate help. TIA.
My dynamic_css.php;
0) {
// select a random index from the file list array
$imageNumber = time() % count($fileList);
// assign the filename for that array index to the $img var
$img = 'http://www.teerthyatri.com/images/'.$fileList[$imageNumber];
$css = "#header { background-image: url(http://www.teerthyatri.com/images/'.$img.'); }\n";
// tell the browser what we're sending
header('Content-type: text/css');
// and write out the css
echo $css;
}
?>
I like how this script works in Firefox and it works fine for loading a single page. However, when I use this script for multiple secondary pages pages I find that Internet Explorer loads a random image initially and then saves it in cache. A new image will appear only on browser reload.
Is there a good way to prevent IE from caching the image or telling it to reload the css on the pageload?
Nice script, worked well on my site, thanks
Thanks for posting this script, works really well on my site which is under development.
Tip to try if you have problems is using Firefox developer bar > Edit CSS and it will show you the errors if there are any.
@bizzy - a quick and dirty hack is to add a unique querystring parameter to the image. For example:
In the dynamic_css.php file change the $img assignment to:-
$img = 'images/'.$fileList[$imageNumber].'?'.time();
@sully and MJY - thanks!
An alternative to the Developer Toolbar is the Firebug extension, which I am finding more and more useful each day.
Can this script be applied to the background of the browser page or does it just work inside of a webpage?
Thanks
I tried the script and get this error; Warning: Cannot modify header information - headers already sent by (output started at /home/deerwood/public_html/style/dynamic_css.php:7) in /home/deerwood/public_html/style/dynamic_css.php on line 60
#header { background-image: url('images/15-golfers-DSC_0060.jpg'); }
Any idea why
I'm using Wordpress and I uploaded dynamic_css, but where do I put the small import statement? I put it at the head of my index, that didn't work so I put it at the top of my Header file… that didn't work either. Anyone have any suggestions?
There was a previous post that asked the exact question I have without an answer:
How do I get this to put a random image in a table cell?
I appreciate the time taken to provide a response.
Hey Lafinboy,
I have the same problem as John. The @import… doesnt seem to work, you can check my test site. If I surf to the dynamic_css.php page, it seems to work well…
Could you help me out?
@ponyack - the random background can be applied to any element that can have a background applied to it through CSS.
@neonix - There are specific plugins for Wordpress that handle random header, but if you want to give this script a try then follow this path.
1 - Place the @import code block immediately before the tag in your themes header.php file.
2 - Either create a folder off the root of your site called 'style' and place the dynamic_css.php file in there, or place the dynamic_css.php file in your themes folder, e.g. wp-content/themes/Raptor_Vs_Zombie/dynamic_css.php. If you place the dynamic_css.php file in your themes folder you will need to modify the @import statement so that it points to that folder as well, e.g.
Make sure your image paths are correct and everything should work!
@Nicky - a simple path fix will see your implementation working again. Change the following part of the dynamic_css.php file:
$img = 'images/'.$fileList[$imageNumber];
so that it reads
$img = 'style/images/'.$fileList[$imageNumber];
@Brett Rodli FloorFiller - this script deals specifically with the issue of background images.
To place random images as part of the content, i.e. using <img> elements, and assuming you are using PHP to generate your pages, you can modify the random_css.php script so that it generates a random image path for use in your <img> element.
To achieve this, remove the following lines from the dynamic_css.php file:
// tell the browser what we're sending
header('Content-type: text/css');
// and write out the css
echo $css;
and use the $img variable in the src attribute of the <img> element. For example:
man i can't figure how to use this. im a complete noob so be easy with me. where do i put the dynamic_css.php folder. how do i put it on my site. sorry for the dumb questions but im totally lost lol.
Hey Juanbo, no problem. I would suggest to place the dynamic_css.php file in the same folder as your other style sheets. That way you can match the image folder paths to the same as are being declared in your main style sheets. Change id references to container elements to apply the image backgrounds to to suit your page templates and you should be good to go.
Good luck!
Hi Lafinboy and thank you for this script. It works like a charm
I will use it in the new version of my website, and I'm sure it will be appreciated.
Thanks again!
Hi Lafinboy,
Nice script. I was wondering if you could help me with a problem i am having?
I am trying to basically set up some script as follows:
I need to have an initial fixed background image to appear on page load with random images to be implemented as the background image on refresh (from a pool of say 5 images)..
can you help? :p
thanks
Mark
Hey Mark - quickest suggestion that comes to mind would be to use a session cookie to determine whether to show a fixed image or random image. you would need to modify the dynamic_css.php file so that it checks for the existence of the cookie each time the script is called. If the cookie exists then use the random image script, otherwise show the static image.
If you need help with the script mail me directly at Scott at this domain.com.
Dear Sir:
First of all, many thanks for putting this great script for the internet community.
I'm not a programmer and know nothing about the scripting language, but have been desperately trying to find a similar script that would help me rotate the title image of my installed theme for my Xoops website.
Just wonder if you could take a bit of your precious time in looking at the theme package (http://allergy.kmu.edu.tw/..temp/greens.zip). The script line for placing the title image (main_img.jpg) can be found in both /greens/theme.html (line 56) and /greens/style.css (line 149). However, I really would like to randomly rotate the image displayed (using those is its /greens/images directory) whenever users access to my website. Being without any knowledge of scripting language, I had blindly tried inserting the script you had provided into places I thought would make the change I want, but it all turned out in vain.. Any suggestion/direction would be highly appreciated!!
cheers,
Marc
@ Marc - I've made some modifications to the script to make it's installation and use a little easier. As for your particular requirements, I have packaged up the response and sent directly to your mail. I haven't worked with XOOPS before, but the methodology looks comparable to many other systems I have worked with. Hopefully the solution provided will work 'out of the box' for you.
Dear sir:
Many thanks to your kind and prompt response to my inquiry. However, I haven't seen your email arriving my mailbox as yet. Could you re-send it to me (bhchen@kmu.edu.tw) again at your convenience? Appreciated per usual.
-Marc
I can't seem to get it to work. I'm sure I have a comma in the wrong place or something
Hi, I'm another one of those Noobs asking dumb questions, sorry
For my blog i use a non-standard template, and the code for background image looks like this:
body {
background : White url(http://wilkesron.googlepages.com/golden-2.jpg/golden-2-full.jpg) no-repeat fixed top left;
What i'd LIKE to do is rotate the background through about 7 jpg. images i have hosted on a GooglePages website.
If you could tell me how to change the code accordingly, I'd be really grateful.
Hope you can help!
Hey Marissa - maybe you got your issue sorted out, maybe not. If you need help let me know.
Mr Cherry, my Northern Beaches friend, not sure that the solution above will work for you on a Blogger account. What will work for you, and seems to be the standard implementation used by Bloggerites, is to use a Javascript array to generate a random style. The example shown below can be modified to suit, and should be placed in the head section of your template, immediately before the closing head tag.
< ![CDATA[
// select a random image from an array and apply
// to an element in a Blogger template
// assign the name of the element to apply
// the background image to here
var el = "body"; // eg: el = "#header"
// assign the images to be used here
var bgimg = new Array(
"http://wilkesron.googlepages.com/X1.jpg/X1-full.jpg",
"http://wilkesron.googlepages.com/blue-man.jpg/blue-man-full.jpg",
"http://wilkesron.googlepages.com/sink-template.jpg/sink-template-full.jpg",
"http://wilkesron.googlepages.com/drinker-template.jpg/drinker-template-full.jpg",
"http://wilkesron.googlepages.com/pink-eyes.jpg/pink-eyes-medium.jpg",
"http://wilkesron.googlepages.com/man-ray.jpg/man-ray-full.jpg",
"http://wilkesron.googlepages.com/rubble-template.jpg/rubble-template-full.jpg"
);
// That's it! Enjoy!!
var random = Math.round((bgimg.length()-1)*Math.random());var str = " { background: url(\""+bgimg[random]+"\") no-repeat top left } ";document.write('<style type="text/css">'); document.write(el);document.write(str);document.write(");
]]>
</script>
I'm thinking this would be great for my Joomla! site, replacing the big Joomla banner at the top of the default template (a png file). This is the header part of the appropriate .css file:
#header {
float: left;
padding: 0px;
margin-right: 2px;
width: 635px;
height: 150px;
background: url(../images/header_short.jpg) no-repeat;
}
file name is template_css.css
How can i load a random image from a numbered set instead of header_short?
Hi guys,
Not sure if this was addressed or not, but I was having trouble getting my random headers to appear on one of our Wordpress blogs. It would simply load up a blank background like John Dille was saying.
My dynamic_css.php file started to render correctly once I made sure to add at the beginning and end of the file.
Then make sure your call to your dynamic_css.php file has double quotes around the URL portion and a semi-colon at the end. If copied and pasted code off this webpage, some of that stuff may have been lost in the process.
Once I saw that, I got it to work fine.
Nice script, thanks for the lesson, Lafinboy.
at the end without any of the spaces.
Hello,
I am having a problem getting this fantastic script to work. Maybe because it is so late at night. If you have some time if you could glance at my work to see if you can catch a simple mistake on my part that would be great.
html page
in the section
@import url("dynamic_css.php");
————————————–
dynamic_css.php
// Set up
$imgFolder = "/images/random_images/";
// the path from the sites root to the image folder created at 3 above
$element = "nav";
// the css ID of the element to apply the background image to
—————————————-
css
#nav {
position: absolute;
top: 0;
left: 0;
width: 252px;
padding-top: 292px;
background: url(images/pic_1.jpg) no-repeat;
thanks for taking your time to look at this
Cheers,
Wiktor
Hi Wiktor
It looks like the PHP tags have been missed when copying/pasting the code into your dynamic_css.php file. To fix, replace line 1 in the dynamic_css.php file with
and replace the very last line with
Make sure your path to the random image folder is correct, and all should be good.
Hi Lafinboy,
Thanks for your help that was a simple mistake that I did probably due to the late .. well umm … early hour.
For some reason though I cant get it to work I tried different things but with no results. I guess I will stick to the javascript rotator.
Many thanks for the quick replay.
Cheers,
Wiktor
Hello,
I'am Pascal Rumph from the Netherlands.
(I hope my english isnt as bad as my css/html/php knowledge)
As my knowledge of building sites is very small I'am using iWeb to create a simple website. I want to give the homepage a more dynamic look with random background images (they must be tiled). So I was trying to implement your code on my website but failed to get it working. I have surfed the web and read and re-read your site several times to find something I did wrong but I couldn't find it.
When I published the site on my local harddrive I tested it with the proper folder-paths but it didn't work. And before I uploaded the site changed the paths to match the server paths. I used Dreamweaver to do this. As far as I can see the script isn't working because I did something wrong. Do I need to change/upgrade my provider with PHP?
Does youre script work with the stuff iWeb puts out?
Can you please tell me what I must correct to enjoy your great work?!
If I have to send my files let me know…
Thanks,
Pascal
Hi Pascal, your English is way better than my Dutch!
There are a couple of issues that may be at work here. The first is that the pages do need to be PHP pages to work. The easiest way to test this is to change the .html extension of your page to .php. If the oage still views correctly then your hosting account has PHP available.
The second issue is the same as the previous commentor - the opening and closing PHP tags from the dynamic_css.php file are missing. I have modified the code block in this post for that file, so copy and paste into your file again.
The third (and fourth) issues are that you have an extra / in front of the couple of paths. Specifically, in the @import statement in the
section of your page, so it should actually be
. And also in the dynamic_css.php file, where you declare the image folder, should read
I hope that helps to get you running. Let me know if I can help any more.
Hello Lafinboy,
Thank you for the quick reply!
I changed the issues you suggested.
I also changed de test-site to another server wich should work with PHP. (http://phpinfo.dds.nl/)
If nescesairy I can change it from PHP4 to PHP5?
Maybee i shouldn't try to do things I don't understand….
It still doesnt work?
http://www.style.dds.nl/test/Site/BURORENG.html
If the configuration is now correct what could be wrong?
If the iweb content doesn't work with the dynamic_css.php do you know another option to get the background change at random? Maybe an other script or work around?….
Many thanks in advance
Pascal
Hi Pascal
You're so nearly there. First, change the file extension of the homepage (and any other page you want this to work on) to .php:
Then change the
element to give it an ID attribute and remove the inline styles:
The final step is to fix a minor error in the code of the dyanmic_css.php file. On line 67 replace the
with
Make sure the
and
variables in dynamic_css.php are set the the random images folder and randbody respectively, and everything should finally work.
I hope we are very close to a solution to making it work. This is what I am getting now?
Parse error: syntax error, unexpected T_STRING in /nfs/vsp/dds.nl/s/style/public_html/test/Site/BURORENG.php on line 1
I did the fixes you suggested and replaced all BURORENG.html with BURORENG.php
(with MassReplaceIt)
Maybe there is something wrong with my folder structure? Or maybe the links are not pointing at the wright files? I placed a text version of the structure below. The content of the ˘folders is visible. The 'random' folder contains the images I like to display randomly on the home background.
———————————-
index.html
˘Site
˘BURORENG_files
BURORENG.css
BURORENG.js
BURORENGIE.css
BURORENGMoz.css
dynamic_css.php
BURORENG.php
›Dierenpark_Emmen_files
Dierenpark_Emmen.html
›Economischmagazine02_files
Economischmagazine02.html
›Economischmagzine01_files
Economischmagzine01.html
feed.xml
›Gasunie01_files
Gasunie01.html
›Gasunie02_files
Gasunie02.html
index.html
logo.ico
›Media
›Raar_en_gek_files
Raar_en_gek.html
›Rajasthan_en_Groningen_files
Rajasthan_en_Groningen.html
˘random
rand01.gif
rand02.jpg
rand03.jpg
rand04.gif
rand05.gif
›Routine_en_Gewoonte_files
Routine_en_Gewoonte.html
›Rumph_en_Gerritsen_files
Rumph_en_Gerritsen.html
›Ruw_en_Gaaf_files
Ruw_en_Gaaf.html
›Scripts
———————————-
The corrected configuration is at
http://www.style.dds.nl/test/Site/index.html
and the old one is moved to
http://www.style.dds.nl/test2/Site/index.html
Hope you can help me once more?
I see I am taking a lot of space on your website and of your time…
Greetings,
Pascal
ps. (if nessesairy I can .zip the test-site 3.2mb and send it to you for futher inspection?)
Lafinboy,
a small extension on my last post…
as the error talks about line 1 in BURORENG.php I deleted the XML declaration.
As far as I can read on different posts on the internet, this shouldn't be a problem?
If I leave the encoding attribute out, the XML parser will treat the document as UTF-8.
After doing this the parsing error is gone but the script for 'CSS Random Background Image Rotation' still isn't running like planned?
Hope to hear from you,
Pascal
Hello Lafinboy,
While waiting for your reply on my last posts I found the following errors, but can't seem to fix the problem. (accesing: http://www.style.dds.nl/test/Site/BURORENG_files/dynamic_css.php)
Warning: opendir() [function.opendir]: Unable to access //http://www.style.dds.nl/test/Site/random/ in /nfs/vsp/dds.nl/s/style/public_html/test/Site/BURORENG_files/dynamic_css.php on line 51
Warning: opendir(//http://www.style.dds.nl/test/Site/random/) [function.opendir]: failed to open dir: No such file or directory in /nfs/vsp/dds.nl/s/style/public_html/test/Site/BURORENG_files/dynamic_css.php on line 51
Warning: readdir(): supplied argument is not a valid Directory resource in /nfs/vsp/dds.nl/s/style/public_html/test/Site/BURORENG_files/dynamic_css.php on line 54
Warning: closedir(): supplied argument is not a valid Directory resource in /nfs/vsp/dds.nl/s/style/public_html/test/Site/BURORENG_files/dynamic_css.php on line 64
Can you please help? (Hope I am not sounding to desperate, because I am
Thanks,
Pascal
Lafinboy, it's been a while since I have got your last reply. In the meantime I tried different stuff put still no succes. When I try to acces: http://www.style.dds.nl/test/Site/BURORENG_files/dynamic_css.php
There is still an error message:
Parse error: syntax error, unexpected ';' in /nfs/vsp/dds.nl/s/style/public_html/test/Site/BURORENG_files/dynamic_css.php on line 67
Please, I hope you have time to help me…
Hi Pascal - sorry it's been so long. I've been away for a few days, but am back now and ready to get you sorted out. First, if can email your dynamic_css.php file (scott at thought-after dot com) I can check that out for you. If that still doesn't work then I'll contact you directly.
i have been looking at your script….. im not exactly good at this… all i know where to replace….. the script above where exactly should i replace…… the different color parts r kind of confusing for me, i dont know wut i need to do to it.
I have the script working - thank you - it is perfect for my website. But I can't make the image rotate on it's own - it only changes when refreshed.
Here is the element from my css sheet:
#containerleft
{
float: left;
width: 350px;
height: 350px;
background-image: url(/testing/randomimages/.$img.) no-repeat;
border-right: 20px solid #FFF;
padding: 10px;
}
If you can give me any insight - I'd truly appreciate it, as this code seems to be perfect for what i'm wanting to acheive. Thank you for your hard work!!
Hi Jolyn - this script is a purely server side solution, and as such will only refresh the image when the page loads.
Hi there,
Great script, got it working, though need some additional css an the background
The bgimage is now loaded without any additional instructions:
$css = "#$element { background-image: url('".$img."'); }\n";
I want to apply the next css to the bgimage:
repeat-x top center #F2F9FD
(as in the original css : background: url(../images/header.jpg) repeat-x top center #F2F9FD;)
Could you help me to hack the dynamic_css.php to do so ?
TIA
grds
Kees
Hi Kees Janisse - you have two options here. The first is to modify the style declaration for the element in the original stylesheet so that the attributes are declared individually:
#element {
background-image: url(imagepath/imagname.extension); /* a default image */
background-position: top center;
background-repeat: repeat-x;
background-color: #f2f9fd;
}
The advantage to this option is that even without the dynamic_css file the background will still work.
Option two is to modify the style declaration in the dynamic_css.php file:
$css = "#$element { background: #f2f9fd url('".$img."') repeat-x top center; }\n";
My advice would be to use use option one, though the final choice is yours.
thx Scott
works perfect !!
The script works great, but stops working if I tab any of the code or add in additional comments. Are there limitations on the code formatting or white space you can have in the PHP doc?
Thanks!
I'm working on a site now and I'm agonizing over getting this code to work for a background image in a table. Please help because this does exactly what I want it to do (in theory).
Here's the section of my php page that I changed (changebackground.php):
// Set up
$imgFolder = "/backgrounds/"; // the path from the sites root to the image folder created at 3 above
$element = "menuback"; // the css ID of the element to apply the background image to
// That's it!! Nothing below this line needs to be changed
Here's the style code in the head of my index.php page:
@import url("changebackground.php");
And here's my preexisting css for the background image:
#menuback {
background-image: url('backgrounds/menuback.jpg');
background-repeat: repeat-x;
}
Hello,
I've tried every conceivable permutation of urls, etc but can't get it to work. I imagine that it is not being invoked properly. Here's relevant code from my index.php file:
————————————————-
" />
id) {initEditor();}?>
" rel="stylesheet" type="text/css" media="all" />
" rel="stylesheet" type="text/css" media="all" />
@import url("/css/dynamic_css.php");
————————————————-
Can you help?
-Andrew
Sorry about the previous post. The code snippet did not display properly.
Here is is again:
" />
id) {initEditor();}?>
" rel="stylesheet" type="text/css" media="all" />
" rel="stylesheet" type="text/css" media="all" />
@import url("/css/dynamic_css.php");
–>
The only problem that I can come up with is that within the head tags of my index.php file, "@import url("/css/dynamic_css.php");" is not the correct.
Thoughts,
-Andrew
Sorry for wasting space. Apparently I can't cut and paste code.
Hi,
Excuse the "__" in the code but I believe its the only way I can enter it in the post.
The problem site is joomla. Within the index.php file I have entered the line:
Within the dynamic_css.php file, the path to the image folder is:
/joomla/templates/des_main/images/headerimages/
The sites root is http://www.frydesign.com
With this combination the page is broken and displays the code rather than rendering the page.
But it appears that something right is happening since I could see this line in the page's source code:
#header_{_background-image:__url('/joomla/templates/des__main/images/headerimages/header_green_peach.jpg')__no-repeat;__}
If I change the image folder path to "/images/headerimages/" for instance, the page renders but, of course, the background image change does not work.
I wonder if the problem is with $_SERVER['DOCUMENT_ROOT'].
I'll leave the site on for a couple of days so you can investigate.
Thanks in advance…
-Andrew
I do template conversions and have used this code on several with no problems.
Then one day I needed to test php 5 and to do this my host requires this to be placed in the .htaccess file " AddType x-mapp-php5 .php ".
With php 5 enabled this way the random images stopped.
I did change $css to
$css = "#$element { background-image: url('".$img."'); background-attachment: fixed; background-repeat: no-repeat; background-position: top center; }\n";
Any ideas on php 5 changes that might be needed. Thank you for your time.
Hi Scott,
I've got next issue
for reasons of the damn PNG bug on ie5&6 I want to use another background image folder in case the browser is IE5or6, so I guess I can load a different dymamic_css.php file in case of… , let's say dynamic_IE6_css.php
To load a different css file i usuaslly use next javascript:
if ((navigator.appVersion.indexOf("MSIE 5")>0) || (navigator.appVersion.indexOf("MSIE 6")>0)) document.write("
u know how to combine this with:
@import url("/path/to/dynamic_css.php");
Or maybe , even better, how to built in some (IE5&6) browser detection script directly into the dynamic_css.php file !?
thx in advance !
rgrds
Kees
Hi,
I am having a problem as Wiktor was but i have my php tag in.
Here is what my code looks like.
html page
in the section
@import url("dynamic_css.php");
————————————–
dynamic_css.php
// Set up
$imgFolder = "/images/random_images/"; // the path from the sites root to the image folder created at 3 above
$element = "header"; // the css ID of the element to apply the background image to
—————————————-
register_a_yacht.css
.header {position: absolute; background: url(images-random-images/yatch-image-swap-1.jpg) no-repeat;}
If you could have a look at the site and tell me where i have gone wrong that would be great. PHP / CSS is new to me can you help?
Many thanks, John
I use a different way to get my random background image, since this code didnt help me on my Server.
I have a php file wich is a little bit different then this one :
<?php
//Setup
$base_dir= '/srv/www/htdocs';
$out_dir = '/html/pics/backgrounds/';
$img_folder = $base_dir . $out_dir;
//Do the Work
$out = null;
//Search only for *.gif files
$extensions = 'gif';
$extensions = explode('|', $extensions);
$files = array();
if($img_folder == ") {
$img_folder = './';
}
$handle = opendir($img_folder);
while(false !== ($file = readdir($handle))) {
foreach($extensions as $extension) {
if(preg_match("/\." . $extension . "$/x", $file)) {
$files[] = $file;
$x ;
}
}
}
// Close the directory handle
closedir($handle);
if(phpversion()
I include this file in my index.php at the top( include('path/to/file/random_bg.php'); ).
Then i use this in the of my index.php :
BODY {
background: url("'.$out.'") no-repeat;
background-position: 100% 100%;
background-attachment: fixed;
background-color: #E8E8E8;
font-family: Batang;
font-weight: bold;
font-size: 12pt;
}
Note : Everything is still in the and echo ' '; tags.
This way it works for me.
I'm having a problem with your script.
After some instant reloads there is no image displayed. Sometimes ths happens very often, sometimes not.
Actual testing page:
http://www.zonewicz.de/index2.shtml
Any suggestions.
Very much thx, dietmar
Dietmar I went to your site link and and went thru the pages and randomly updating the pages.
On the first page I did a page source and your " import url to dynamic_css.php " was there in " index2.shtml ".
When your problem occurred, on links, I did a page source and " links.html " was missing the " import url to dynamic_css.php ".
So I went back to your home page, with menu, and did another page source and the file changed to " index.shtml " and it was missing " import url to dynamic_css.php ".
Then I manually went back to " index2.shtml " and all was fine.
It appears only file " index2.shtml " has the import url and some of your other pages dont have it. Plus your home button calls " index.stml " when it should call index2.shtml ".
You need to check you menu links. Plus the " import url " needs to be in all pages where you want to see the random image in header.
Oups, I forget to tell: only the "index2.shtml" is for testing purposes. All the other sites are working well, but without same new improovememnts, like the image roatation.
So when you hit the reload button several times, sometimes there is no image loaded by the dynamic_css script.
dietmar
To Dietmar. Thanks for info.
Checked your site again and saw two things.
When the header image fails right click the area and pick " view background image ". The name of the image has changed. Example " header3.jpg " becomes " ._header3.jpg ".
Now your server thinks that is a good file. Just type in
http://www.zonewicz.de/img/random/._header3.jpg
You dont get a 404 error.
Make sure your random image folder only has good image files in it.
I also noticed your element is called " container " and in your css file you also have " #container ". When I did my random images I placed all my css for the random images in the " dynamic_css.php " file on the $css line.
I have problems with getting the images to change? i have kept the script as is,but i only get one image.
test Site:
http://www.jdwebsolutions-testarea51.com/registerayatch/about-register-a-yacht.html
any help would be great.
Thanks
John
John I see in your css file this.
#header{ background-image:url(images/random-images/yatch-image-swap-3.jpg)}
Remove that line. Your $element is also " header " in the random php code as seen on this line of your page code
Thanks a lot!
I found the problem: I'm working on a Mac, and the ._header3.jpg is the thumbnail file.
Now the problem should be fixed.
dietmar
Thanks ed for the quick response
i have taken out that line from the css, but now i do have any images
Thanks for any help i dont have that much experience with PHP or CSS
John try this.
On your import url change link to " ("/dynamic_css.php") ".
Your just adding the " / " to it.
With no images the choice is the link to dynamic_css.php is wrong or the link to the images folder is wrong.