random background image

You are currently browsing articles tagged random background image.

A while ago I posted a solution for generating CSS random background images, which provided a PHP server side solution for adding random background images to stylesheets on the fly.

Since it's initial posting the solution provided there has been tweaked and fine tuned based on use and reader feedback. A lot of the feedback and comments were about the inability for readers to use that particular solution because they did not have access to modify the PHP source code. One such example is that of Bloggers, who have access to the Blogger templating system, but not the code.

In response to this feedback I have put together a free random background image script generator tool, which will generate a self contained block of Javascript which can be pasted into any template or web page, to provide random background image selection and application to a single element on that page.

Comments and feedback are encouraged, as are links from any sites that may find a use for the script!

Tags: , ,

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.

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

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

Tags: , , , ,