Most websites like to use rotating banners to add an extra appeal in their header. To make this work, all we need to do is get all the images from the specified directory, choose a random image, and present it to the browser. First, we need to create some sort of configuration for this:
$directory = './images/';
$accept = array('gif', 'png', 'jpg');
$deny = array('file1.jpg', 'file2.gif');
Next, in order to scan through the directory, we would need to use scandir(). Using the filters above, we can also restrict the files that are in the directory using array_filter() since the output of scandir() is of type array. The built-in PHP function array_filter() requires an input array, and an optional callback function. A callback function is a function that PHP calls after a certain event. In this case, the event would trigger with every value in the array. We will use the callback option which requires one parameter that will contain the value of the key.
$files = scandir($directory);
$files = array_filter($files, 'filter_images');
global $accept, $deny;
if (in_array($image, array_merge($deny, array('.', '..', '.htaccess', 'index.html'))))
// Remove, because we don't accept those files
$ext = substr(strrchr($image, '.'), 1);
if (!in_array($ext, $accept))
// Remove, because its not an accepted extension
// This image passed the tests
Now we have an array of all of the images we can use for the banner rotator. Because we removed some of the values from the file list, we need to resort the array so that the keys are consecutively ordered from 0 using the function sort(). After this, we will need to generate a random number from the range of the keys using mt_rand(). The reason we are not going to use rand() because mt_rand() produces a “better” random number and is four times faster, according to php.net.
$files = array_values($files);
$rand = mt_rand(0, count($files)); // mt_rand(min, max);
$image = $directory . $files[$rand];
We have selected our image and all that we have left is to output the image to the browser. We need to set the proper content type header and output the contents of the image using header() and readfile().
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $image);
header('Content-type: ' . $mime);
At this point, a random image is displayed when viewing this file. All you have to do next is display it on your page using the HTML <img>tag or using CSS. I will go over both methods.
First, using the image tag, you can do the following:
<img src="banner.php" alt="Banner" />
Next, with CSS, you can do this:
If you want to get more advanced, you can always enhance the filters with REGEX using preg_match(). And, as I said before, for their header to add an extra appeal and other uses. You can wrap a link around the <img> so that whenever someone clicks your header, it redirects them to the homepage. This is a tool most websites use, depending on how it is constructed and looks. I hope you guys have fun with this script!