Feature
Post

Category
Code

Rotating Header Images in PHP

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:

<?php
$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.

<?php
$files = scandir($directory);
$files = array_filter($files, 'filter_images');

function filter_images($image)
{
    global $accept, $deny;

    if (in_array($image, array_merge($deny, array('.', '..', '.htaccess', 'index.html'))))
    {
        // Remove, because we don't accept those files
        return false;
    }

    $ext = substr(strrchr($image, '.'), 1);

    if (!in_array($ext, $accept))
    {
        // Remove, because its not an accepted extension
        return false;
    }

    // This image passed the tests
    return true;
}
?>

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.

<?php
$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().

<?php
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $image);
finfo_close($finfo);

header('Content-type: ' . $mime);
readfile($image);
?>

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:

<style type="text\css">
#banner {
    background-image: url(banner.php);
}
</style>
 <div id="banner"></div>

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!

Download File

  1. By phil.gs posted on May 22, 2008 at 1:08 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Cool technique! I especially like the way the PHP file returns the image directly rather than being part of a larger file. Two things:

    1. I think you have a typo somewhere because you say you’re going to use sort(), but then your code is $files = array_values($files);

    2. What are the advantages of this technique over using client-side javascript to pull a random image? I’m thinking specifically about the case where you’re using the SuperCache WordPress plugin, so you are basically serving static files. Obviously the banner.php file would not be cached, but it seems like you’re creating additional load on the server by having to run the PHP file each time. With JS, you’re offloading and distributing a lot of the randomization and processing to the individual browsers.

  2. By Karn Edge posted on May 22, 2008 at 8:25 pm
    Want an avatar? Get a gravatar! • You can link to this comment

    Any word on Prebuilt3 coming out? :) Great article btw.

  3. By Richard posted on June 18, 2008 at 2:20 am
    Want an avatar? Get a gravatar! • You can link to this comment

    I’d just name all the banners as banner1.png, banner2.png etc, then just do:

    <img src”/path/banner.jpg” alt=”"/>

    This makes things simpler though you’d need to manually update the “4″ in this case if you had a different no. of banners.

  4. TrackbackdiarioTHC | Rotar imágenes del header con phpcarakan | web 2.0 y otras cosas. » Noticias breves

    Your words are your own, so be nice and helpful if you can. If this is the first time you're posting a comment, it might go into moderation. Don't worry, it's not lost, so there's no need to repost it! We accept clean XHTML in comments, but don't overdo it please.