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. Recursive sort-by-modification-time
    This certainly isn’t rocket science, but it also is certainly not something you want to type more than once. find . -type f -printf '%T@\t%p\n' | sort -n | cut......
  3. 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!......
  4. Dailed-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......

This entry was posted in Technical HOWTOs and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Additional comments powered by BackType