Random Background images with CSS and PHP

This is a PHP function I use to load a random image from a folder and display it as the background.

//functions.php
//written by Bill Heaster
//theCreator at ApexLogic d0t net

function displayBackground()
{
	$dir = 'backgrounds/';
	$cnt = 0;
	$bgArray= array();
		
	 		/*if we can load the directory*/
	if ($handle = opendir($dir)) {
		
		/* Loop through the directory here */
		while (false !== ($entry = readdir($handle))) {
		
		$pathToFile = $dir.$entry;
		if(is_file($pathToFile)) //if the files exists 
		{	
			
			//make sure the file is an image...there might be a better way to do this
			if(getimagesize($pathToFile)!=FALSE)
			{
				//add it to the array
				$bgArray[$cnt]= $pathToFile;
				$cnt = $cnt+1;
			
			}
			
		}	
		
	}	
	//create a random number, then use the image whos key matches the number
	$myRand = rand(0,($cnt-1));	
	$val = $bgArray[$myRand];
	
}
closedir($handle);
echo('"'.$val.'"');

}

A basic outline of what is happening here. $dir is a variable that holds the location of all your images. A while loop is used to go through all the files in the directory. The filenames are then placed into an array, a random number is generated and used to point to the key of the array. You can use the code by placing it in a css style tag like the example below.

<head>
	<link rel="stylesheet" type="text/css" href="style.css">
	<style>
	body
	{
	background: url(<?php include'functions.php'; displayBackground();?>) no-repeat center center fixed; 
	-webkit-background-size: cover;
	-moz-background-size: cover;
	-o-background-size: cover;
	background-size: cover;
	}
	</style>
	<title></title>
</head>

In the above code we include the functions.php file, then call the displayBackground(). I have only tested this on Firefox thus far. If you have issues let me know.

Leave a Reply