CSS Random Background Image Rotation

Posted May 26th, 2006 by Lafinboy

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

<?php /*** Random Background Images

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:

<style type="text/css"> @import url("/path/to/dynamic_css.php"); </style>

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


100 Responses to: “CSS Random Background Image Rotation”

  1. Faruk responds:
    Posted: June 21st, 2006 at 10:33 am

    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

  2. Joe responds:
    Posted: July 19th, 2006 at 12:13 am

    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?

  3. notsirk responds:
    Posted: August 31st, 2006 at 9:09 am

    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!

  4. David Spinney responds:
    Posted: November 2nd, 2006 at 5:26 pm

    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

  5. AmLoQ responds:
    Posted: December 5th, 2006 at 9:34 am

    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?

  6. John Dille responds:
    Posted: December 21st, 2006 at 2:58 pm

    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!

  7. Onkodjinn responds:
    Posted: December 26th, 2006 at 10:21 am

    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…

  8. Onkodjinn responds:
    Posted: December 26th, 2006 at 11:04 am

    –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!

  9. FloorFiller responds:
    Posted: January 9th, 2007 at 3:04 am

    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

  10. muserna responds:
    Posted: February 17th, 2007 at 7:30 am

    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.

  11. Larry responds:
    Posted: March 1st, 2007 at 2:56 pm

    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;
    }
    ?>

  12. bizzy responds:
    Posted: March 13th, 2007 at 2:32 am

    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?

  13. sully responds:
    Posted: March 13th, 2007 at 10:01 am

    Nice script, worked well on my site, thanks

  14. MJY responds:
    Posted: March 25th, 2007 at 8:43 pm

    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.

  15. ponyack responds:
    Posted: April 13th, 2007 at 3:26 am

    Can this script be applied to the background of the browser page or does it just work inside of a webpage?

    Thanks

  16. golfdesign responds:
    Posted: April 14th, 2007 at 9:44 pm

    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

  17. Nionix responds:
    Posted: April 26th, 2007 at 3:25 pm

    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?

  18. Brett Rodli responds:
    Posted: April 27th, 2007 at 4:18 am

    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.

  19. Nicky responds:
    Posted: April 27th, 2007 at 5:49 pm

    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?

  20. Juanbo responds:
    Posted: May 10th, 2007 at 1:19 pm

    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.

  21. Ryuichi responds:
    Posted: June 21st, 2007 at 11:58 pm

    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!

  22. Mark responds:
    Posted: July 13th, 2007 at 12:29 am

    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

  23. Marc responds:
    Posted: July 16th, 2007 at 5:31 pm

    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

  24. Marc responds:
    Posted: July 17th, 2007 at 9:08 am

    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

  25. Marissa Levy responds:
    Posted: July 25th, 2007 at 4:57 am

    I can’t seem to get it to work. I’m sure I have a comma in the wrong place or something

  26. dickcherry responds:
    Posted: August 6th, 2007 at 9:25 pm

    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!

  27. JetClarke responds:
    Posted: August 23rd, 2007 at 1:39 pm

    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?

  28. Web Marketing Consultant in DC responds:
    Posted: October 23rd, 2007 at 7:24 am

    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.

  29. Web Marketing Consultant in DC responds:
    Posted: October 23rd, 2007 at 7:25 am

    at the end without any of the spaces.

  30. Wiktor responds:
    Posted: November 21st, 2007 at 7:44 pm

    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

  31. Wiktor responds:
    Posted: November 22nd, 2007 at 5:35 am

    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

  32. Pascal Rumph responds:
    Posted: November 22nd, 2007 at 9:24 pm

    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

  33. Pascal Rumph responds:
    Posted: November 22nd, 2007 at 11:50 pm

    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

  34. Pascal Rumph responds:
    Posted: November 23rd, 2007 at 7:44 am

    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?)

  35. Pascal Rumph responds:
    Posted: November 23rd, 2007 at 11:08 pm

    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

  36. Pascal Rumph responds:
    Posted: November 28th, 2007 at 6:44 am

    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

  37. Pascal Rumph responds:
    Posted: December 4th, 2007 at 5:33 am

    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…

  38. Random Backround Image - Gigposters.com responds:
    Posted: December 4th, 2007 at 2:56 pm

    [...] this might help __________________ Plink Design [...]

  39. LuckiCharmzXP responds:
    Posted: December 9th, 2007 at 6:27 am

    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.

  40. Jolyn responds:
    Posted: December 10th, 2007 at 3:45 am

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

  41. kees janisse responds:
    Posted: December 15th, 2007 at 12:22 am

    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

  42. kees janisse responds:
    Posted: December 16th, 2007 at 12:19 am

    thx Scott
    works perfect !!

  43. skillet responds:
    Posted: December 18th, 2007 at 3:51 am

    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!

  44. Cavol responds:
    Posted: January 2nd, 2008 at 3:16 pm

    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;
    }

  45. Andrew Fry responds:
    Posted: January 18th, 2008 at 8:40 am

    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

  46. Andrew Fry responds:
    Posted: January 18th, 2008 at 8:51 am

    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

  47. Andrew Fry responds:
    Posted: January 18th, 2008 at 8:55 am

    Sorry for wasting space. Apparently I can’t cut and paste code.

  48. Andrew Fry responds:
    Posted: January 19th, 2008 at 9:29 am

    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

  49. ed harrison responds:
    Posted: January 23rd, 2008 at 12:57 am

    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.

  50. kees janisse responds:
    Posted: January 31st, 2008 at 3:52 pm

    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

  51. John Dibb responds:
    Posted: February 12th, 2008 at 10:35 pm

    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

  52. amtcubus responds:
    Posted: March 8th, 2008 at 2:31 am

    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.

  53. Dietmar responds:
    Posted: March 17th, 2008 at 12:14 am

    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

  54. ed harrison responds:
    Posted: March 17th, 2008 at 12:55 am

    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.

  55. Dietmar responds:
    Posted: March 17th, 2008 at 7:18 am

    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

  56. ed harrison responds:
    Posted: March 17th, 2008 at 8:15 am

    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.

  57. John responds:
    Posted: March 17th, 2008 at 6:34 pm

    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

  58. ed harrison responds:
    Posted: March 17th, 2008 at 11:36 pm

    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

     

  59. Dietmar responds:
    Posted: March 18th, 2008 at 12:26 am

    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

  60. John responds:
    Posted: March 18th, 2008 at 12:42 am

    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

  61. ed harrison responds:
    Posted: March 18th, 2008 at 2:48 am

    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.

  62. jack23 responds:
    Posted: May 27th, 2008 at 2:31 am

    nothing is coming up for me…how do i use this?

  63. GEEK420 responds:
    Posted: June 14th, 2008 at 9:57 pm

    Is it possible to add Macromedia support to this great code?
    The idea is to load the images using a .swf that displays a .flv, thus loading the image quicker and avoid the cacheig of the image.

  64. amtcubus responds:
    Posted: June 30th, 2008 at 3:39 am

    Why shooting the Bear with a Bazooka, when a Rifle would be enough ;)
    This code is as small as it gets. Why should one insert there some flash? It’s something totaly different :)
    You could do all this with flash, sure. But doing it this way with php is first : saver and second : faster.
    Because the Browser of the Person surfing your site wont need to load the flash plugin, then loading the applet wich manages randomizing of the Picture so it can be fiewed.

    If you already do have flash on your site, it surely wont make any difference if there is one more. But for ppl wich aim to have a site wich is fast, the php is the way to go.

    Surely, that flash thingy you said may be fine too. :)
    Regarding the cacheing of files. It’s no difference if your Browser loads a few kb big image file or loads a few kb big .flv file. I would say, it needs more time with the .flv then some random image file.

  65. zac responds:
    Posted: July 3rd, 2008 at 5:53 pm

    Hi … Thanks for the great script and easy to follow directions !

    I tried out Matt’s rotator and this, both work great, but I am having a similar issue with both.

    The first image that will appear, on a browser free of cookies, will be random. Then after a few refreshes the images will be static and not change anymore. I have like 5 images in the pool. Is this normal behavior? Why does it stop after a few refreshes?

    Second I have this same id put on the background of images on numerous pages, however the background image never changes when switching pages, only when I clear cookies and refresh will the image change.

    Any ideas on this? ?

  66. Kees responds:
    Posted: July 12th, 2008 at 4:16 am

    Hello,

    I’m trying the script the whole day now, but can’t get it to work. Is it neccesary to rename the page to .php? I can’t find out what I’m doing wrong.
    Followed everything a few times.

    Testpage: http://www.vddesign.nl/gegevens.php

    Thanks very much

  67. ed harrison responds:
    Posted: July 12th, 2008 at 4:40 am

    On your site ” Kees ” when I view the source code there is no css ” id ” declared.

    Your body ststement is and there is only one ” id ” on your whole page and it does not deal with random images.

    I do see your call to dynamic_css.php.

    I would place below that call something like this ” ” and then a at the bottom of your page.

    Look at line 30 of the above code “– $element = “header”; // the css ID of the element to apply the background image to –” .

  68. ed harrison responds:
    Posted: July 12th, 2008 at 4:58 am

    ” Kees ” I see that home.jpg is missing on your test site.

    It could be you need an id in the following area

    .

    Your primary site url has this

    .

  69. Kees responds:
    Posted: July 12th, 2008 at 5:50 am

    Hello Ed,

    Thank you vey much for your fast response.

    I forgot the id but I tested it with an id before and didn’t work.

    I left the home.jpg away because that is the place where all the other images must come. If I place it, it just shows that image. the strange part is: I tried the javascript generator and dind’t get it to work eather. I doing somthing wrong, I cann’t find out what.

    Now placed an id (named: back), and changed it in de dynamic_ss.php-file. Still no luck.

    Do you got some other idea’s?

    Thabks in advance
    Kees

  70. ed harrison responds:
    Posted: July 12th, 2008 at 7:14 am

    Kees when I attempt to access your ” dynamic_css.php ” I get three errors.

    —-
    Warning xxxxdir(/backgrounds/) [xxxxxx.xxxxdir]: failed to open dir: No such file or directory in D:\www\vddesign.nl\www\dynamic_css.php on line 51


    All three are tied to the path to the images, $path. The error however shows a disk drive ” D: ” in it. You might try a complete http type address.

  71. Kees responds:
    Posted: July 12th, 2008 at 7:49 am

    Hello Ed, thanks.

    I changed the path and also I copied the dynamic_css.php to a directory called “css”.
    I still get this error.
    Why isn’t it finding this file? Ireally don’t get it. Do you have another suggestion maybe?

    thank you very much.

  72. ed harrison responds:
    Posted: July 12th, 2008 at 8:11 am

    When I access your file now I get

    /http://www.vddesign.nl/backgrounds/

    as the image folder.

    The example above says

    $imgFolder = “/images/random-images/”

    thats because its off the root of your domain.

    You want

    $imgFolder = “http://www.vddesign.nl/backgrounds/”
    or
    $imgFolder = “http://www.vddesign.nl/backgrounds”

    Just keep accessing the file only with your browser. If you get an error then change your code for the image folder. When I access mine I get # header with the image. You use back so you should get # back. The dynamic_css.php can be found, its the image folder “/background/” that cant be found.

    ————–

    I also saw this on accessing the background folder.

    “” This Virtual Directory does not allow contents to be listed. “”

    Could be the server your on changes something. Virtual.

  73. Kees responds:
    Posted: July 12th, 2008 at 4:33 pm

    Thanks Ed,

    I changed all the variable items to the original like in the example. Of course I changed that also in my page. Still the same problem. So I’m going to mail my host, so maybe they know what is going wrong. If they have a solution, I will let you know.

    Thanks for your help.

    Kees

  74. ed harrison responds:
    Posted: July 12th, 2008 at 11:23 pm

    Kees I checked the web on some of the included code and found

    $_SERVER-x-DOCUMENT_ROOT-x- changed some symbols -x- is [’ .

    might not function if you are using Apache as an NFS server.

    Several places mentioned a work around for the above code on some host’s.

  75. Kees responds:
    Posted: July 14th, 2008 at 6:28 pm

    Thanks Ed,

    The website is running on a windows server. I arranged an index in the imagefolder so now the folder is OK. Still not working. Still the same problem with the dynamic_css.php. I get the same error when I try to go to this file in the browser.

    I will contact my host again for some suggestions.

    Thanks

  76. ed harrison responds:
    Posted: July 14th, 2008 at 10:52 pm

    Probably best would be to change whats below

    –// build up the path to the image folder –

    The function at the end of that area isnt working

    – $path = $_SERVERxxDOCUMENT_ROOTxx . $imgFolder –

    all it shows is /background/ as the address or a drive letter at beginning.

    You could replace the seven [7] lines of code with

    $path = “http://www.vddesign.nl/backgrounds/”

    In searching web on windows server DOCUMENT_ROOT I found
    quote “” it’s not a good value on Windows/IIS server “” .
    Normally the recommendation was
    quote “” you will have to “hard-code” this line to point to your web_root “”.

  77. Kees responds:
    Posted: July 15th, 2008 at 12:42 am

    Hello Ed,

    Thanks for your reply,

    I replaced the seven lines with $path = “http://www.vddesign.nl/images/random-images/ (because that’s the location of the pics. And of course I changed that in the $imgFolder). De id is in the site called “header”. And the link to dynamic_css.php is also in the site.

    Still no luck. I’m just thinking maybe I have to stop looking because maybe it is not possible to use it. I hope not because it would be a very nice effect for the site. Maybe another script you know?

    Thank you very much, I rally appreciate it!

    Kees

  78. ed harrison responds:
    Posted: July 15th, 2008 at 1:36 am

    Kees could you send me a copy of your code in dynamic_css.php .

    You have now caused a new error which could be a bracket or space in wrong place.

    spam@mangee.net

    This email address allows me to protect from spamers.

    I’ll answer on my normal email.

  79. erik responds:
    Posted: July 21st, 2008 at 1:58 am

    Hey all,

    Great script, I just wish I was advanced enough to implement it. Can someone go to my test site with fireBug:

    http://www.foodologycollective.com

    and tell me how to alter the rotating images to this random script…sorry about this. I have tried everything and just had to search out some expert help

    Thanks!

  80. ed harrison responds:
    Posted: July 21st, 2008 at 12:22 pm

    __erik__

    I looked at your link. I saw no rotating images. So looked at your source code and download your style.css file.

    In the file is element ” #topbanner ” with a url of ” images/rotate/rotate.php “. Is this what you are trying to replace with the code from here.???

    Part of the change would be to replace ” $element = “header” ” with ” $element = “topbanner” in the code at the top of this page. This would point the code at that ID location.


Post a Comment

Enter Your Details:


You may write the following basic XHTML Strict in your comments:
<a href="" title=""></a> · <acronym title=""></acronym> · <abbr title=""></abbr>
<blockquote cite=""></blockquote> · <code></code> · <strong></strong> · <em></em>

  • If you’re a first-time commenter, your response will be moderated.
  • If your response includes a link, it will require moderator approval.
Enter Your Comments:


Note: This is the end of the usable page. The image(s) below are preloaded for performance only.