CSS Random Background Image Rotation

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 PHP to retrieve a random image from a folder, we can generate dynamic CSS 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.
[code lang=”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. @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:

[code lang=”html”]


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

211 comments on “CSS Random Background Image Rotation

  1. hi,
    great Solution. i was looking something similar type but all i need is it the image changes automatically after some time without reload of full page.
    any help is appreciated thanx in advance.

  2. It would be easier to just make your script output a random image every time it gets loaded and then do this –

    #css-selector { background:url(‘/path/to/script.php’); }

  3. hi there.
    great script. i read somewhere its possible to code so that an image cannot come 2 times in a row.. could u implement that?

    best, flo

  4. Hey guys, I know this is an old post but if anyone is still active could you perhaps have a think about this problem for me.

    I’ve implemented this script exactly as described and it works great – except – the image isn’t changing on refresh/reload – it remains the same – UNLESS – I wait about 40 seconds!!

    Aurghhh! Any advice?!

  5. Hi There Scott,

    Me again… are you still checking this site frequently?

    If not, does anyone else know how to do what I’m asking?



  6. Hi Again. Is anyone there? I’d really love to know how to do what I’m asking.



  7. Hi There,

    I’ve implemented your script in a WordPress theme that I’m building locally.

    Instead of using it to change the background for the header, I’ve used it to change the background image I’m using for the dates of my blog posts.

    It works like exactly like it’s supposed to, but now I’m wondering if there’s any way to get it to pick a different image for every post? So, in addition to changing on each page refresh, each post would have a different background image behind the date?


    Thanks a bunch for the code and your help!


  8. Hi,

    I tried your script. It works fine on my local host (IIS). But when I upload it to the web server it doesn’t load the background images.

    Here is the detail
    Windows Web Server.
    root folder is: httpdocs

    Under root folder I have created a folder login.

    All my php files are inside login folder.

    File I am trying to get it work with the background is login.php
    Inside ‘login.php’ file

    @import url(“/login/dynamic_css.php”);

    // table and rest of the stuff are here..

    Inside dynamic_css.php
    $imgFolder = “/login/images/random-images/”; // all my bg images are in random-images folder. file size around 2 MB each
    $element = “body”;

    Inside styles.css

    body {
    // no default background is set..

    So as per above structure it works absolutely fine at the below link of my localhost


    So all the files are inside login folder and login folder is lying at the root folder wwwroot of my localhost and working fine.

    But when I uploaded the same login folder to my web server it’s not working.

    I have tried with the following options in dynamic_css.php file

    $imgFolder = “http://domainname.com/login/images/random-images/”; // it also doesn’t work

    $imgFolder = “http://www.domainname.com/login/images/random-images/”; // it also doesn’t work

    $imgFolder = “/login/images/random-images/”; // it also doesn’t work

    $imgFolder = “../login/images/random-images/”; // it also doesn’t work

    with the following options in login.php

    @import url(“http://www.domainname.com/login/dynamic_css.php”); //doesn’t work

    @import url(“http://domainname.com/login/dynamic_css.php”); // doesn’t work

    @import url(“/login/dynamic_css.php”); // doesn’t work

    A suggestion will be highly appreciated.


    1. Just adding few more warnings..I get from the above code

      when I navigate to dynamic_css.php in the url I get the below warning messages:

      Warning: opendir(/login/images/random-images/) [function.opendir]: failed to open dir: No error in C:\inetpub\vhosts\domainname.com\httpdocs\login\dynamic_css.php on line 47

      Warning: readdir(): supplied argument is not a valid Directory resource in C:\inetpub\vhosts\domainname.com\httpdocs\login\dynamic_css.php on line 50

      Warning: closedir(): supplied argument is not a valid Directory resource in C:\inetpub\vhosts\domainname.com\httpdocs\login\dynamic_css.php on line 59

      But when I navigate to the same dynamic_css.php file on my localhost it’s working fine and giving me the below result.

      #body { background-image: url(‘/login/images/random-images/bg_img5.jpg’); }

      Expecting an early response.

      1. Hi Pradeep, it looks very much like you are experiencing path issues on the production server. First step is to verify that the path you are setting in the dynamic_css.php file is being converted to a correct path.

        You can test this by echoing out the $path variable in the dynamic_css.php file by adding:
        directly after the line that reads:
        $path = $_SERVER['DOCUMENT_ROOT'] . $imgFolder;

        If the path is not correct adjust it until it is. If you still experience issues send me the actual URL so that I can debug from my end.

        1. Thank you so much for your quick response. I really appreciate it.

          After adding this line

          when I navigate to the url below:

          it gives me this result:

          Here is the link I am trying to set the background image

          And the images are exactly in the below destination folder of my production server.


          And the dynamic_css.php, styles.css and login.php all these files are in login folder.

          Please suggest.

          1. Hi,

            Thanks for ur help. However, I talked to my hosting company and they have also set the permission but I’m still not able to get rid of the warning. They said there may be some problem with your coding, please check that.

            Now I’m stuck in the middle. Pls help if it’s possible for you.

            Any help will be greatly appreciated.

            Thanks again…

          2. Did you ever solve this problem cuz it seems like so long. Anyway, I managed to do the same thing you were doing, except, in the login.php file, I included the style tag at the top of the page before the php codes and the rest worked wonderfully well. Also, thanks alot #Lafinboy.

  9. I was reading some of the comments here, facing the same problem: the css wouldn’t load up. After some troubleshooting I decide to create a page to verify my document root:

    Turns out it was incomplete, instead of pointing to: /var/www/folder/imgfolder, it was pointing just to: /var/www

    Meaning: I had to fell the variable $imgFolder with: folder/imgfolder/

    that fix my problem



  10. I’m trying this out for a charity (test pages at: response.org.uk/2012/ ). They may not want it, but I had fun, thank you.

    having fiddled with the image path for a while (good way to test it is to stick the url of dynamic_css.php into the browser. You’ll get messages of various types saying something along the lines of “that folder doesn’t exist, stupid”. Translated means, you’ve put the wrong image folder path in, try again. When you get it right you’ll see just ‘stylesheet’ css).

    bla. this is my way of saying ‘thanks’. Thanks.


  11. Thanx, took me a while. But I finally got it working here:

    I think the instructions were too vague and that is why some of us had difficulty getting it to work. But I was able to figure it out thru trial and error. Very Cool!

  12. I’ve tried so many variations on this and am not getting anywhere. I wonder if you can help me out.

    Here’s the code in my WordPress header.php file:

    @import url(“dynamic_css.php”);

    Here’s the code in my dynamic_css.php file:

    // Set up
    $imgFolder = “http://redtail.net.au/rainbow/wp-content/themes/rainbow/bgimages”; // the path from the sites root to the image folder created at 3 above
    $element = “body”; // 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 body code in style.css:

    margin: 0px;
    padding: 0px;
    font-family: Verdana, Arial, Helvetica, sans-serif;
    color: #595959;
    line-height: 1.5em;

    style.css, dynamic_css.php and the bgimages folder all sit in the same folder

    I’ve tried every possible variation on the path, I’ve tried to place the images into a div called “header” but all to no avail. Can you tell me where I’m going wrong?

    1. Hi Ramapriya, from a quick look at the site in question it appears you have removed the dynamic_css files, so I can’t offer any exact remedies.

      A couple of things to point out though:

      The @import directive needs to be in a <style></style> block after all other style blocks in the head

      The @importurl path should be /rainbow/wp-content/themes/rainbow/dynamic_css.php

      The $imgFolder path should be /rainbow/wp-content/themes/rainbow/bgimages/
      The $element variable needs to be set to an element with a matching ID value, so your body element would need to look like <body id="body"> to work

      Hopefully the items above will assist in getting the random backgrounds set up correctly for you.

      1. Thanks for this. I noticed that the tags seemed to disappear when I posted the comment *scratching chin* :o)

        Most importantly it was the which was the real solution for me. Can’t believe I didn’t spot it so thanks heaps. It works great and I will certainly use it in future. There are plug-ins for WordPress which achieve this now available and I think that I must have been testing one when you visited my site. They work pretty nicely too.

        One thing people might like to know is if they don’t want a repeating background that they can style this in their style sheets.

        Thanks again, it’s a neat solution.

  13. Hi,
    I’m building a website pro-bono for a fantastic non-profit women’s organization in afghanistan and though I’ve followed all the directions, I can’t get the script working. Perhaps Joomla is mucking it up.

    Here’s the page: http://www.womenforafghanwomen.org/joomla/

    my paths are correct, but I’ve noticed the css background image doesn’t have an ID, only a class.
    Can you help?

  14. hi there.
    i´m using the wordpress arras theme.
    i did it like you told us in your description but it won´t work for a changing background image.
    if i put @import url(“/dynamic_css.php”); into header.php it will only bring up a “banner” but no full background.
    so i´m an absolute noob in php but maybe it is because the “$element = “background”;”

    maybe any idea?

  15. Thank you for this neat script, which I plan to use to rotate the banner background image on a site powered by PHP-Fusion (CMS). I have got it working OK on my local test site, but only with IExplorer. In Firefox, Chrome or Safari the site won’t load properly. Since it works in IE, I guess I must in some sense have the script set up correctly, but I guess IE is more forgiving than the other browsers. Any suggestion as to what might need tweaking>

    Best wishes for 2011

    1. Answering my own question, Firefox is telling me it hasn’t loaded “dynamic_css.php” because the MIME type is “text/html” not “text/css”; so, for some reason, the line “header(‘Content-type: text/css’);” isn’t doing its job.

  16. Hi,
    I’ve been trying to get this code to work all morning…would you mind taking a look at my testpage to see what I am doing wrong?
    the site is:


    after creating the php, I modified the code with:

    $imgFolder = “/images/”;
    $element = “rotate”;

    and also inserted the code below to the proper locations:
    @import url(“/path/to/dynamic_css.php”);

    I followed all the steps to the best of my ability but nothing appears. Please view my source code and help! Thanks

  17. In case of using a div there has to be a width and height attribute in the css. If for some reason want the div to resize based on the size of the image modify the $css= line and add the line of code to get the size of the image like below.

    //get the image size for sizing the div
    $image_size = getimagesize($path.$fileList[$imageNumber]);

    //sending image sizes as width and height for div
    $css = “#”.$element. “{ background-image: url(‘”.$img.”‘); ” . ” width:” .$image_size[0]. “;” . “height:” .$image_size[1]. ” }\n”;

    That will make the div resize along with the image if you are using it for styling some kind of picture frame and have different sized images.

  18. been reading your site for several days. really enjoy what you posted. btw i will be doing report regarding this topic. do you know any blogs or online forums in which I might get more info? thanks a ton.

  19. Great script! I’m surprised there’s no WordPress plugin adaptation, but that’s ok, I did get it to work! Question, which i hope is simple. Is there a way that I can just specify a parent directory and have it also pull in all images from all the sub directories in that parent directory? (I want to use all my WordPress Content Uploads as random background images). That’s all I’ve got. Let me know if there’s a trick to it. Thanks!

    1. Hi Jason, WordPress plugin may be on it’s way soon!

      It would be possible to modify the script so that the generation of the files array is encapsulated in a recursive function which would gather all files from the parent and child directories. Examples of recursive functions can be found at php.net

      Depending on the number of files/directories I would suggest that a cached list of files would be a better option.

      1. cool. looking forward to that plugin! I’ll check out php.net. I’ve got very limited knowledge of how to form PHP (like none…but i do follow instructions pretty well) but maybe it will reveal itself. I guess I just want it to read sub-directories out of laziness so I never have to touch the code again 😉
        Why is not using cache for this plugin a bad idea? (I’m sure the answer is somehwhat obvious…just trying to determine if it could be a real problem and not a hypothetical one)

  20. Hi, I inserted into my header.php page, right after the link to my regular CSS page, like this:

    <link rel="stylesheet" type="text/css" media="all" href="” />
    @import url(“dynamic_css.php”);

    which doesn’t seem right. i think i have my paths and variables all set correctly otherwise, though. do you know why it isn’t working?

  21. Hi Aquarafairy, the path to your image folder needs to be relative to the root of the site. You have a full URL in there. So in the dynamic_css.php file change:
    [code]$imgFolder = “http://www.metrowestcaresforkids.org/LowellTwoSides/wp-content/themes/simplefolio/images/doctor/”;[/code]
    [code]$imgFolder = “/LowellTwoSides/wp-content/themes/simplefolio/images/doctor/”;[/code]

  22. Lafinboy,

    I have tried everything and cannot get this script to work with my wordpress site.

    In the header.php i have included the path:

    @import url(“http://metrowestcaresforkids.org/LowellTwoSides/wp-content/themes/simplefolio/dynamic_css.php”);

    the tag is named

    In the dynamic_css.php file, the paths are:
    $imgFolder = “http://www.metrowestcaresforkids.org/LowellTwoSides/wp-content/themes/simplefolio/images/doctor/”;

    $element = “rotate”; // the css ID of the element to apply the background image to

    in the doctor folder are 2 images ‘1.jpg, 2.jpg’ for testing. The only way 1.jpg shows up is if my body tag styled with css:

    body {
    font-family: ‘Lucida Grande’,Verdana,’Bitstream Vera Sans’,Arial,sans-serif;
    background-color: #bbdedf;
    background-position: center top;

    the rotate ID currently has no style applied. I’ve tried both ways and still nothing.

    If you could help that would be great. ALso if I try to call the dynamic_css.php in the browser it says the following:

    Warning: opendir(/var/chroot/home/content/t/u/f/tuftsmwmc/html/http://www.metrowestcaresforkids.org/LowellTwoSides/wp-content/themes/simplefolio/images/doctor/) [function.opendir]: failed to open dir: No such file or directory in /home/content/t/u/f/tuftsmwmc/html/LowellTwoSides/wp-content/themes/simplefolio/dynamic_css.php on line 48

    Warning: readdir(): supplied argument is not a valid Directory resource in /home/content/t/u/f/tuftsmwmc/html/LowellTwoSides/wp-content/themes/simplefolio/dynamic_css.php on line 51

    Warning: closedir(): supplied argument is not a valid Directory resource in /home/content/t/u/f/tuftsmwmc/html/LowellTwoSides/wp-content/themes/simplefolio/dynamic_css.php on line 60

  23. Lafinboy,

    Your script is awesome and does exactly what I was looking for. However, I’d like to make the background image scalable, full background image. Do you think this is possible? Do you know of any other solutions that would work? I’m looking for something similar to Children Now’s web site: http://www.childrennow.org/index.php/

    Thanks again!

    1. Hi Dave, glad you found the script useful. Background images in CSS aren’t scalable, at least not yet! The best you could do is have a large background image positioned 50% 50% in the main element. This way, as the page size increased more of the vertical/horizontal portions of the image would be displayed. Depending on the image(s) you are planning on using this may be a workable solution.

      The ChildrenNow site is Flash based, with the background being a scalable vector image, which is how they have that effect working.

  24. hi! the script works like a charm… but i wanna know if theres a way to additionally “attach” a particular background-color to each image. Example: when a a red gradient background image (red.jpg) loads, then the script assigns a “background-image: #D00000” css property to the body, or when a blue gradient bg image loads, then the script assigns a “background-image: #3bd000” css property…. etc.

    Hope someone can help me.

  25. Hello,

    This coding is exactly what I am trying to do to my site and I am very new to this so I’m having trouble. I have the import statement for dynamic_css.php in the head of html page. I have the page linked to a style sheet in the head successfully so that I can specify a background image for the whole site through the style sheet in an element I titled “body”. I am not able to successfully link the dynamic_css.php file I created with your code to these elements. I am thinking I am entering the path’s incorrectly. I have not published this site to the web yet so I am working locally on Dreamweaver and every other path I have used so far is a path from the site root, or the folder where all of these filed are stored. My “Background” images folder is a subdirectory of this file.

    My path’s are as follows:
    $imgFolder = “/Background/”; // the path from the sites root to the image folder created at 3 above
    $element = “body”; // the css ID of the element to apply the background image to

    I created the css file with the body element solely for the purpose of using this code. It contains the followin element and nothing more above or below:

    The head of my html page (index.htm) contains these elements:

    @import url(“/dynamic_css.php”);

    Am I missing something in the css file? I assumed the php file added the property to the body element that specified the random background. Do I need a background-image property? Or are my pathways incorrect? Sorry I can’t provide a URL. Any help would be greatly appreciated. Again, I have figured out everything I know so far on my own so I may be lacking in some of the technical details needed to make this work.


    1. Sorry to keep replying, obviously the html tags are correct as they are not showing up. I deleted the dynamic_css.php file to start over and it warned me that my index.htm was linked to it so I’m assuming I have linked it correctly. I know also that I have linked the stylesheet I made just for this purpose correctly because I can add a background image to the style and it appears. When I remove the background-image property from the “body” element of the style sheet I get no images. I have tried every configuration for the pathway to the “Background” folder where I intend to keep the images and that currently holds two images for testing. I’m am thinking I made a mistake when creating the dynamic_css.php file. I merely opened a blank .php file and pasted the entire code above into it and saved it as dynamic_css.php. I just don’t know what I am missing. I’ve scoured the forum here and found several similar issues but couldn’t fix it with previous posts. This script would really tie my site together so I’m am eager to make it work. Thanks again for any assistance.

  26. Hello.

    I was able to accomplish the random background with a different method, it’s not as dynamic as this one, I have to put the file names in an array. since I’ll only have a couple images, that is fine.



  27. Hello,

    Hopefully someone can help me. I’m trying to use this script to rotate the overall site background. I’ve tried everything I can think of to get this to work. Could my problems be related to the fact that the body section of the CSS file doesn’t start with a # (as seen below)?

    BODY {
    background: #012d4a;
    background-image: url(img/background3.png);
    background-position: top center;
    background-repeat: no-repeat;
    font-size: 1em;
    font-family: verdana;
    margin: 0;

    This is the background image that I am trying to rotate… is it possible? Any help would be greatly appreciated!



    1. Hi Chris, the script attaches itself to an element identified by an id attribute. Quick fix is to add an id attribute to your body element, and use this id in the script.

      1. Hello and thanks for the quick reply! Just so I’m clear on your instructions, you’re suggesting I make up an ID for this script, lets say we call it rotate. I would then do something like in my pages?

        Would I need to have the #rotate id added to my css file as well?

        I’m very new to css and php, sorry 😛

        1. I’m going to be “that guy”, and reply to my own post… So, im my css file, I left the body section empty

          Body { }

          I then added a rotate id

          #rotate {
          background: #012d4a;
          background-position: top center;
          background-repeat: no-repeat;
          font-size: 1em;
          font-family: verdana;
          margin: 0;

          From there, I did as you suggested, and put the id in my body tag . Everything worked, except this script. The background colour was correct, so I am assuming the rotate properties are applied to the body. However, I end up with no images.

          I have dynamic_css.php located in the same directory as my css file, though I’m not sure how it knows the name of the css file? Fortunately, I only have one css file so i guess that shouldn’t be an issue. I put the following in the dynamic_css file;

          $imgFolder = “/img/rotate/”; (I also tried img/rotate/)
          $element = “rotate”;

          My image directory contains two images, both .png files.

          I can’t think of any other useful information 🙂

          Not sure where I could be going wrong?



          1. Hey Chris, have you included the @import style directive in the head of your page? It looks like you’re doing everything else right. Do you have a URL I can have a look at so I can help debug?

  28. I really want to use this in a WordPress theme…which has it’s own header.php file, so that’s where I’m putting the @import code like this:

    @import url(dynamic_css.php);

    I can’t get it to work, and it may be because I don’t understand paths very well….I’ve no idea where the root of my site is, especially as I’m testing this on a MAMP localhost installation, not online. The URL of my (local) site is:


    but if you followed the file structure to dynamic_css.php, it would be something like this:


    So I’ve no idea what the path ‘from the site’s root to the image folder’ is!

    Any help appreciated.


    1. I’m also trying to use it in my WordPress theme, which also has it’s own header.php. I feel I did everything as directed above, and I even tried customizing it a bit, but nothing seems to work.

      Does anyone know how to get this, or any other random background image generator to work with WordPress. I can’t seem to find anything.


  29. Hi. I’m currently an IT student doing a school project.
    I’ve tried to implement your code into my website but somehow, I can’t get it to work.
    Is it okay if you could spare some time to take a look at my coding?

  30. Hello All,

    Well, I found this PostNuke-Zikula CMS and I would love to have my background image changing, at every time the page refresh or by after some time. But, I can not find any .HTML file to add the code, and as you will see, I am clueless on this programming and code stuff.

    The only thing I found on the Zikula folders, is a file where the background image is loaded is named Style.css and the line say:
    body {

    background-image: url(../images/background.jpg);

    . etc.

    So, Can any one help me with this?


  31. Hi,
    Firstly I must say how good the free script is that is generated… works a treat!

    I found your free script after searching the internet for 2 days solid and trying various others.

    The thing is I have been looking for a script that does what yours does but changes the background image every few seconds and not on page load or refresh.

    I’m on my third day now looking at codes; CSS, Javascript, php, html you name it, chopping bits out of one and trying them in another but still can’t achieve the desired effect.

    It’s seems simple enough to do for foreground images and there are plenty of options to choose from on the internet, but nothing for background images!!!

    I have a quick search facility on my proto-type web which contains a couple of drop-down menus and a min/max amount input box.

    I want to have a background image behind this which rotates between several images but can’t for the life of me achieve it.

    I need to call the script that does it from within a <td tag. for example <td id=”whatever”

    or <td width=”700″ height=”400″ background-img: url=”a php file with rotating images in

    If this is possible?

    Is there any chance you could adapt the script which is generated free to rotate images every few seconds or an amount of time chosen?

    I think if you can you will boost traffic to this site 10 fold as I have come across hundreds of other wanting to achieve the same thing while I have been searching.


    1. <img src="/images/image.jpg” alt=”OAVS Australia’s cheapest domain names and web hosting plans” width=”156″ height=”301″ border=”0″ />

      Place your images in a folder ‘images’ and name your images image1.jpg, image2.jpg, image3.jpg etc.

      Make sure rand(1,3) reflects number of images in the folder.

      1. Ouch all my PHP code was stripted out. Here is I go again

        <img src="../graphics/homepage/image.jpg” alt=”Australia’s cheapest domain names and web hosting plans” width=”156″ height=”301″ border=”0″ />

        Please take the extra spaces out

  32. If I wanted to use this script to add random backgrounds to more than one div, how would I do so without having to have multiply copies of your scripts to put the bg’s in certain div’s.


    1. Hi Willis – you should be able to munge the $element variable value to achieve this. Assuming that you want to apply the background image to three elements with the ID’s element1, element2 and element3, you could set the value to $element = "element1, #element2, #element3";

      1. That would work but I’m wanting to pull a different image into each of 4 div from 4 different image folder so none of the divs will ever have the same background loaded at once.

  33. Hello.

    I have been working on updating a template from Joomla 1.0 to 1.5 that is using your dynamic header rotator – in my case. I am close to getting it working and not very familiar with PHP or javascript, really. Can you take a look and point me in the right direction? I would appreciate your assistance.

    Many thanks,

    1. Hi Jason, happy to help you out with your integration. Send me an email (scott dot swabey at this domain name) with a link to your site with your current integration and we’ll work through it.

  34. Hi again,

    Well it did not work on my remote testing server, but when I uploaded to client server from different provider than mine it worked without problems.

    Thanks for the script

  35. Sorry about my last comment, i allready found out what was wrong, but now i have another question how can i use this to change the background of the body?, instead of a css ID thank you!

  36. Hi, i tried this in my wordpress site, i added this to the header <!– @import url( /dynamic_css.php ); –> , and i put the dynamic_css.php file on my theme directory in wordpress, but nothing happened any idea???? thank you very much

  37. Hi all, I’ve just returned from two weeks of R&R in beautiful Bali. Give me a day to get back into the groove and I’ll post responses to each of your questions.

  38. Hi … i m trying to use your script to change the background to my blog. The is the css id that I would like to be changed .. any ideas why it doesn’t work?

    1. Hi Chris, looks like you haven’t set up the relative path to your background images folder correctly. try setting the $imgFolder variable to “/dwd/ncfh/03/bg_test/bg/”.

  39. Hi! I try to work with the script,but its just not work for me,is there any chance that some one can check my site,and to see where is the problem?
    tnx alot! 🙂

  40. Lafinboy,

    Thanks for posting this great script. I successfully installed it on my
    css/php website!
    But I have one question: I would like to have a link and an alternate
    text to this background image. Is that possible?
    Or would I have to change from your php/css script to some javascript?

    Thanks in advance

  41. Hi Kristy – no problem, let’s see if we can get you through this step by step.

    Step 1: in your html page, replace [code lang=”html”]

    [/code] with [code lang=”html”]


    Step 2: in your html page, edit the <body> element so that it reads [code lang=”html”][/code]

    The reason for step 2 is that the dynamic_css script targets an element on the page by it’s ID value. Give that a go and see what happens.

  42. Hi there,
    Thanks so much for the quick response. I changed the import directive as you stated I should. But as far as the body in the CSS goes, there is not a number sign… I’m still confused. I thought by directing the dynamic_css to the body it would load automatically…
    I’m a total newbie!

  43. Hi Kristy – change the css @import directive in your site to [code lang=”php”]@import url(“/assets/dynamic_css.php”);[/code]
    You have referenced an element with an ID of ‘body’ to be targetted by the dynamic css, but there is no element with that ID on your page. Either add an ID attribute to the
    <body> element, or simply target the body in the stylesheet by removing the #.

  44. Hi there,
    I can’t seem to get this script to run properly. I’m not sure where the problem lies…. No doubt it is me. (lol) So. I followed the instructions and still can’t get it going. Please help me out.
    The url is politicsoflonely.com

  45. @ Fco Javier – the problem with you installation is totally my fault! I recently rebuilt this blog and overlooked the replacement of fancy quotes in code blocks. It is the fancy quotes in the code you have copied that is causing the problem. I have fixed the issue on the blog – you should now copy the dynamic_css.php code again and paste it into your file. Once done everything should be good.

  46. I have been fighting with your code (and several other php codes) for randomice my wordpress background… but until now without success… so if you can help me….

    The website (in construction)… http://www.pkipublicidad.com

    Our code

    (cant send the code… wp-ids block my message), please send me a e-mail direction to send you the code…

    Thanks for all… and if you need more info… please ask me.

  47. __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.

  48. Hey all,

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


    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


  49. 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.


    This email address allows me to protect from spamers.

    I’ll answer on my normal email.

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


  51. 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 “”.

  52. 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.


  53. 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.

  54. 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.


  55. When I access your file now I get


    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/”
    $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.

  56. 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.

  57. 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.

  58. 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

  59. ” 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


  60. 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 –” .

  61. 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? ?

  62. 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.

  63. 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. 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.

  65. 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

  66. 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.


  67. 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


  68. 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


    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.

  69. 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.


  70. 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.

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

    $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

    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.

  72. 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”);



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



    .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

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

  74. 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.

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

    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:


    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…

  76. 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.


  77. 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?


  78. 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;

  79. 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?


  80. 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:
    /* original css file */
    #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:
    /* 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.

  81. 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 ?


  82. 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:
    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!!

  83. 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.

  84. 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.

  85. 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 😉


  86. 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,

  87. 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.

    The corrected configuration is at

    and the old one is moved to

    Hope you can help me once more?
    I see I am taking a lot of space on your website and of your time…

    ps. (if nessesairy I can .zip the test-site 3.2mb and send it to you for futher inspection?)

  88. 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: [code lang=”PHP”]http://www.style.dds.nl/test/Site/BURORENG.php[/code]

    Then change the
    [code lang=”PHP”]body[/code]

    element to give it an ID attribute and remove the inline styles:
    [code lang=”PHP”][/code]

    The final step is to fix a minor error in the code of the dyanmic_css.php file. On line 67 replace the
    [code lang=”PHP”]>[/code]

    [code lang=”PHP”]>[/code]

    Make sure the




    variables in dynamic_css.php are set the the random images folder and randbody respectively, and everything should finally work.

  89. 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?


    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


  90. 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 head section of your page, so it should actually be @import url("http://www.ontwerpgoed.nl/test3/Site/BURORENG_files/dynamic_css.php");. And also in the dynamic_css.php file, where you declare the image folder, should read $imgFolder = "http://www.ontwerpgoed.nl/test3/Site/random/";

    I hope that helps to get you running. Let me know if I can help any more.

  91. 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…



  92. 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.



  93. 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 <?php /*** Random Background Images and replace the very last line with ?>

    Make sure your path to the random image folder is correct, and all should be good.

  94. 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”);



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



    #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



  95. 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.

  96. 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?

  97. 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.

    [code lang=”javascript”][/code]

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

  99. 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.


  100. @ 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.

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


  102. 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.

  103. 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



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

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

  106. 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.

  107. @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:
    [code lang=”php”]$css = “#header { background-image: url(‘”.$img.”‘); }\n”;

    // tell the browser what we’re sending
    header(‘Content-type: text/css’);
    // and write out the css
    echo $css;[/code]and use the $img variable in the src attribute of the <img> element. For example:
    [code lang=”php”]

    @Nicky – a simple path fix will see your implementation working again. Change the following part of the dynamic_css.php file:[code lang=”php”]// assign the filename for that array index to the $img var
    $img = ‘images/’.$fileList[$imageNumber];[/code] so that it reads[code lang=”php”]// assign the filename for that array index to the $img var
    $img = ‘style/images/’.$fileList[$imageNumber];[/code]

  108. @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. [code lang=”css”]@import url(‘wp-content/themes/Raptor_Vs_Zombie/dynamic_css.php’);[/code]

    Make sure your image paths are correct and everything should work!

  109. 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?

  110. 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.

  111. 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?

  112. 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

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


  114. @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:-

    [code lang=”php”]// assign the filename for that array index to the $img var
    $img = ‘images/’.$fileList[$imageNumber].’?’.time();[/code]

    @sully and MJY – thanks!

    An alternative to the Developer Toolbar is the Firebug extension, which I am finding more and more useful each day.

  115. 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.

  116. 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?

  117. 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;

  118. 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.

  119. 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.


  120. 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…

  121. Hi John – the @import directive (including opening and closing style tags) needs to be placed in the [code]head[/code] 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.

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

  123. 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.

  124. 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?

  125. 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.

  126. 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?



  127. 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.

  128. 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?


  129. 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?

  130. 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 .



Comments are closed.