Using Random Images using CSS and PHP
I want my page’s background, navigation bar, and and main content to be randomized together on my main phpVMS site. Now, I don’t want to touch any HTML, just do it in CSS. My background is split into three files, spanning 3 divs, even though it’s one image.
My CSS looked like this:
[css]
#body {
background-image: url(images/topbanner.png);
}
[/css]
So the image has to be random, but it has to be matched up. Sounds like a job for PHP. First thing we do, is create a folder in our /images directory:
[code]
/images/bg/1.png, 2.png, etc
[/code]
Next we create our PHP file to pick out a background image for us. I called it “bgimages.php”, and placed it in the root of my site (one directory up from /images). Next we change out background-image in CSS to the PHP file (remembering that paths in CSS are relative to the CSS file; I placed it with my CSS file):
[css]
#body {
background-image: url(bgimages.php);
}
[/css]
First we want to setup the total number of images we have, and then the path to our images:
[php]
$total = 4;
$basepath = ‘images/bg/’;
[/php]
We next randomize:
[php]
$num = rand(1, $total);
[/php]
And then finally show the file:
[php]
readfile($basepath.$num.’.png’);
[/php]
readfile() will just throw the entire file out, without processing, which is what we want to do.
Another thing we can do, instead of using the $total and $basepath, is to use the glob() function:
[php]
$files = glob(‘images/bg/*.png’);
$num = rand(0, count($files));
readfile($files[$num-1]);
[/php]
glob() will do a wildcard match in a directory, and return an array of files which match. The above will match any file ending in the .png. glob() is slower though, and since I keep my images in a separate directory, and don’t change much, I decided to go with giving the total number. The downside is whenever I add an image, I have to change the total number of images, but since that’s not that often, it’s okay. It also saves some load on the server from using glob().
The whole script:
[php]
<?php
header(‘Content-type: image/png’);
$total = 4;
$basepath = ‘images/bg/’;
$num = rand(1, $total);
readfile($basepath.$num.’.png’);
[/php]
Not too shabby for 4 lines.