Amber Weinberg: Freelance Web Developer specializing in semantic WordPress, Mobile, CSS and HTML5 Development

The Blog

Ordered Image and Background Switcher Using PHP & jQuery

Posted on 10/29/09 in blog, development about , , , ,

Yesterday I took on building a completely customized website using a bunch of  jQuery plugins, Mootools script, PHP and implementation into WordPress for $200 and a featured blog post. Why so cheap and for whom? This I will tell you in a post when the site launches. What I want to show you today is a quick and neat feature I used on that site. My client wanted a background that changed in a certain order, every time you refreshed the site OR hit the next button. Easy enough right? He also wanted to be able to control these images and update them himself – not so easy with the budget and time I had allocated to the project, that is until a help of a few programming friends came along!

The PHP

First you need to figure out what folder you want the images coming from. My folder was images/bkg/. Give your images a sequential order in which you want to see them: bkg1.jpg, bkg2.jpg, etc etc Any image you upload to this folder will automatically be included in the switcher.

Inside of this folder of images, you need to upload the php script. This was given to me by @107designs and modified to display in order by @smelly_fish. Name it something like rotate.php:

<?php
$folder = '.';
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$img = null;
session_name("babooshka");
session_start();
$nmCounter = $_SESSION['nmCounter'];
//print 'my counter: ' . $nmCounter;
$nmCounter++;
$_SESSION['nmCounter'] = $nmCounter;
if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}
if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $folder.$imageInfo['basename'] )
) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (
isset( $extList[ strtolower( $file_info['extension'] ) ] )
) {
$fileList[] = $file;
}
}
closedir($handle);
if (count($fileList) > 0) {
$imageNumber = $nmCounter % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = @imagecreate (100, 100)
or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}

?>

The HTML

The HTML is very simple. All you need to do is call the php script with a simple image tag (yes you read that right):

<img src="images/bkg/rotate.php" alt="W00t!"/>

What this does is it echos the binary data of the images in the folder and displays them. This should work perfectly now, switching your backgrounds in the order you gave them on refresh.

If you remember though, the client also wanted the backgrounds to switch with the click of a button without refreshing the page.

The jQuery

Give your button and your PHP image tag an ID. I went with #nextButton and #rotateBkg:

<img id="rotateBkg" src="/images/bkg/rotate.php" alt="W00t!" />
<a id="nextButton" class="next" title="Next Image" href="#"></a>

After you’re jQuery library link of course, place this bit of code:

var count = 0;
$(document).ready(function() {
$("#nextButton").click(function() {
$("#rotateBkg").attr({src : ""});
$("#rotateBkg").attr({src : "/images/bkg/rotate.php?q=" + count});
count = count + 1;

});

Refresh the page and voila!

The Results

Not only does this proceed in order, it also has a memory! If you hit the next button 3 times and then refresh, the refreshed site will display the 4th image, instead of starting over! (Super cool, huh?) We had a caching problem at first, where it refused to update the image, this has been resolved by another friend of mine @IsaacVanName, who changed up the jQuery event to prevent caching.

This works in IE6+, FF3+ (and probably lower), Safari and Chrome!

About the author
Amber Weinberg specializes in clean and semantic XHTML, CSS and WordPress development. She has over 10 years of coding experience and is pretty cool to work with. Amber is available for freelance work, so why not hire her for your next project?

6 Awesome Comments

  1. Mike says:

    @envyeconomy (Mike)

    Its always nice that once you work on a project, you share. Very appreciated.

    about.com has some code similar as well. I like how customizable your code is, Theirs is more random.

    Excellent post.

  2. BigAB says:

    Hey,
    Small thing but I wouldn’t use a global variable with such a common name as “count” just to prevent caching. You never know where someone is going to forget to add a “var” or something and get strange bugs they can’t figure out because of that global setting of count (this happens more than you’d think) or various other things that can happen if you mix scripts from other people into your sites and keep adding global scope variables.

    Because I don’t see “q” being used anywhere in the PHP I’ll assume it’s just there to prevent the caching so you’d be better off using something this
    [pre]
    $(document).ready(function() {
    $(“#nextButton”).click(function(e) {
    $(“#rotateBkg”).attr({src : “”});
    $(“#rotateBkg”).attr({src : “/images/bkg/rotate.php?q=” + Math.random()});
    });
    });
    [/pre]

    …also I don’t know if there’s a reason to clear the src before changing it, so you could probably lose that line too (though I didn’t test it, so try it out I suppose).

    If you need an other “programming friend” just email, though due to my job I am specialized in front end (JavaScript and CSS). love the site and the blog, keep cranking it out, it’s good stuff.

  3. Amber says:

    @BigAB Thanks for the suggestion, I’ll keep that in mind :)

  4. Harald says:

    Thanks for this great code. It works like a charm, but as usual one would always want to do a little more. So do I. Is there any possibility to add a link to each image?
    Thanks again for charing this code.

  5. Joseph says:

    Thank you for this great post, That’s exactly what i was looking for. only one question, can i have this code to work for a container with a background image using css. Thanks again for sharing this clean piece of code.

Leave a Reply