Random images as a background in HTML

by Kevin on February 6, 2009
in Random Knowlege

A nice wee gem that Alex Peake informed me was possible. The problem: you want a randomly chosen image as a background but don’t want duplication in your css.

In your css file:

background-image: url('images/background.php');

Create the file referenced above with this code:

<?php
    $numofimages = count(glob("*.jpg"));
    $imagenum = rand(1, $numofimages);

    header("Content-Type: image/jpeg\n");
    header("Content-Transfer-Encoding: binary");

    $fp=fopen("headerimage". $imagenum .".jpg" , "r");
    fpassthru($fp);
?>

and voila, random images as a background with the bonus of being able to throw in a new image without having to do any more coding.

This code assumes that your images are called headerimageX.jpg where X is a number.

Comments are closed.