Simple PHP image rotation script

This blog has a rotating header — if you visit /header/ and bounce on reload, you’ll see a series of random images. Here’s how it works:

The header is added to a div with the following CSS:

#headerimage{
  background: url("/header/") center center no-repeat;
}

/header/ is a directory in ~/public_html/. It contains a bunch of similar-sized images, along with the following index.php file:

<?php
$pattern = '/\.(png|gif|jpg|jpeg|svg)$/i';
$dh  = opendir('.');
while (false !== ($filename = readdir($dh))) {
  if (!is_dir($filename) && $filename[0] != '.' && preg_match($pattern, $filename)) {
    $files[] = $filename;
  }
}
closedir($dh);
$file = $files[rand(0, count($files) - 1)];
header('content-type: '. mime_content_type($file));
readfile($file);
?>

It’s pretty simple. It

  1. looks for image files in the same directory (lines 2-9)
  2. chooses one at random (line 10)
  3. sets the mimetype of the response based on the image’s filename suffix (line 11)
  4. sends out the file’s contents (line 12)

What’s nifty is you can turn this into an ultra-lightweight slideshow by adding one line:

header('refresh: 5');

after line 11 (the mime_content_type header). There isn’t any transition between the image changes, but we’ll leave that for next time.

Related posts:

  1. Simple Image Slideshow with jQuery and PHP
    I really liked Jon Raasch’s jquery-powered slideshow, but integrating it into a page requires a bunch of steps: Add the jQuery library Add the slideshow javascript function Add the CSS......
  2. Simple Log4J eclipse template
    Do you use eclipse and log4j? Do you have a template to add a static Logger instance in classes? Do you have to manually add the import? HA! NO MORE!......
  3. Simple 301 or 302 redirects with Apache or PHP
    It behooves you to make sure you’ve only got one URL that serves a given piece of content–so says google. But what if you’ve got a bunch of domains that......
  4. Dialed-in Rails script/console with pretty printing and history
    Edit (as root) your /etc/irbrc: # Some default enhancements/settings for IRB, based on # http://wiki.rubygarden.org/Ruby/page/show/Irb/TipsAndTricks   unless defined? ETC_IRBRC_LOADED   # Require RubyGems by default. require 'rubygems'   begin require......