PHP: creating an automatic and dynamic banner

In this article I will illustrate a relatively simple PHP application, but which contains a couple of useful techniques: creating an automatic and dynamic banner.
To keep it simple, it will simply be a series of images, but these techniques could really be used for anything at all. Nonetheless, it will include a couple of fancy features (well, I wouldn’t be writing an article about it otherwise): the images will appear in random order at every page refresh and they will be automatically pulled from a folder, so that to add or remove images we won’t have to edit any code.

So, here’s the script:

// Banner image randomization

// Settings
dir = 'images/banner_imgs/';image_types = array('.gif' => 'image/gif',
                '.png' => 'image/png',
                '.jpg' => 'image/jpeg',
                '.jpeg' => 'image/pjpeg');
num = 4;

// Do it!imgs = scandir(dir); # get the images from the folder
if (imgs) {

    shuffle(imgs);# randomize the ordercontent = '';
    i = 0;

    foreach (imgs as img) {
        if (!is_dir(img)) {
            if (in_array(mime_content_type(dir .img), image_types)) { # if it's an accepted file type...content .= '<img src="' . dir .img . '" height="90px" />' . "\n"; # ...output it
        }// end if(!is_dir)

        if (num > 0) {
            if (i ==num) { # when the required number of images has been output...
                break; # ...exit the loop...
    }// end foreach

    echo content; # ...and print

}// end if(imgs)


Let’s go through this step by step.


The settings part defines three variables: $dir, the directory (folder) to get the images from, $image_types, an array of accepted image MIME types for images, and $num, the number of images to display. Setting the former to zero or a negative number will display all images in the folder, as we will see.

I find it often useful to put all settings/parameters variables at the beginning of the script, in order to make it easier to change them if necessary.

Do it!

This is the ‘active’ part of the script, the one that actually does it all.

Scan the directory
$imgs = scandir($dir); # get the images from the folder
if ($imgs) { ...

Here, we use the scandir function to get all the files in the given directory. This function takes a directory string as input and returns an array of filenames and directories in it, or false if it failed.
To program defensively, we then check that it ran successfully.

Randomize the order of the files and start looping
shuffle(imgs);# randomize the ordercontent = '';
i = 0;

foreach (imgs as $img) { ...

If there were no errors, we use the shuffle function to randomize the order of the files.
Next, we define the $content and $i variables, which will store the output image tags and current number of images output respectively.
Then we begin looping through all the files, one at a time, with a foreach loop.

Check the file is an image and output
if (!is_dir(img)) {
    if (in_array(mime_content_type(dir . img),image_types)) { # if it's an accepted file type...

        content .= '<img src="' .dir . img . '" height="90px" />' . "\n"; # ...output iti++;

If the file is not a directory (!is_dir($img)), we need to check that it is of an accepted file type.
To accomplish this, we use the in_array function to see if the MIME type of the file (obtained with the mime_content_type function) is in the $image_types array.

If the file validates, we can append the corresponding image tag to the $content string and increment the counter.

Stop at the given number of images and print the output
        if (num>0) {
            if (i == num) { # when the required number of images has been output...
                break; # ...exit the loop...
    } # end foreach

    echocontent; # ...and print

} # end if($imgs)

At each iteration, we have to check that we have not reached the maximum number of images yet.
So, if the $num parameter is greater than zero (this allows us to output all the images in the folder by setting $num to zero) and we have reached the maximum number of images, we will exit the loop with the break; keyword.
Once the loop is complete, we’ll print the images and… there you have it! Enjoy tweaking and fiddling with this code to get even better applications!

This is relatively simple example, but it demonstrates a few techniques which can be quite useful.

As always, please comment if you have any questions, tips or have found a bug!


Here are a few links you might find useful:

See an example of this script a work:
scandir function:
shuffle function:
mime_content_type function: