Monthly Archives: September 2010

Random page background image

Just for something different, here is a bit of PHP which will cause a random background image to be loaded every time you refresh your page. The image is chosen randomly from a directory making it easy to add or remove new images without needing to update the HTML.

This code should go in place of the <body> tag in your HTML.
// Set this to the path where your images are stored.
$bgdir = '/images/backgrounds';

// Test the extension of a file to see if it is an image file.
function isImageFile($src) { return preg_match('/^.+.(gif|png|jpe?g|bmp|tif)$/i', $src); }

// Get the list of all files.
$dirlist = scandir($_SERVER['DOCUMENT_ROOT'] . $bgdir);

// Put all the file names into an array.
$imgs = array();
$preload = '';
foreach($dirlist as $file)
{
if(isImageFile($file))
{
$preload .= "   rn";
$imgs[] = $file;
}
}

// Generate a tag with a random background image URL.
$url = $bgdir . '/' . $imgs[array_rand($imgs)];
print "rn";

// Pre-load all the other images so subsequent page loads will be fast.
print $preload;
?>;