Photo of the Hour Script

By | July 21, 2012

I was just looking around some of the more interesting posts on the forum and I came across one of Joe’s (krakjoe) simple yet incredibly useful scripts. Someone wanted a script that “randomly” selects a photo from a directory and displays it for an hour on a site. I, being a not-so-great programmer at the time, had suggested using a cron script to run every hour. If I saw the question today, I would probably suggest using a text file and saving the date an image was last generated and to select a new image if that was from too long ago. But Joe was the one that came up with code and, after analyzing it, I think it’s a much better, contained version that fits inside a single script using the power of pseudo-random number generators.

Before boring you anymore, here’s the code:

<?php
function hour_based_image_from_directory($directory)
{
    if (($time = strtotime(date("Y m d H"))))
    {
        srand($time);

        if (($scan = @scandir($directory)))
        {
            return sprintf("%s/%s", $directory, $scan[rand(2, count($scan))]);
        }
    }            
}

if (!headers_sent())
{
    header("Cache-Control: must-revalidate");
    header("Expires: ". gmdate("D, d M Y H:0:0", time() + 3600) . " GMT");
    header("Content-type: image/gif");

    if (($image = hour_based_image_from_directory("gallery")))
    {
        if (readfile($image) != filesize($image))
        {
            readfile("error.gif");
        }
    }
    else readfile("error.gif");
}

?>

Naturally, you can also use this method for non-images like articles or links saved in a MySQL database. You can even modify it to select a new item ever day or every month by modifying line 4:

    if (($time = strtotime(date("Y m d H"))))

This selects an item every day (I removed the hour):

    if (($time = strtotime(date("Y m d"))))

We can even select one every year:

    if (($time = strtotime(date("Y"))))

In case you couldn’t tell what I changed, just leave the date element that will remain constant for the duration of the display time. For example, if we select one every year, the year number remains constant from Jan 1 to Dec 31 but changes with each new year and so that’s what we leave. You could even make it change every decade by rounding the year but I won’t go that far since I’m sure some of you haven’t even lived a decade yet. ;)

Note that Line 18 which sets the cache expiration time also needs to be modified (especially for anything shorter than 1 hour).

So there you go — be creative and go out and make good use of it!

Credit goes to Joe Watkins (krakjoe on Space Socket).

Edit: I went in an reformatted everything to make things simpler and somewhat more readable. Keep in mind, this was from a forum post — probably done in a couple of minutes. The idea here is more important than the code that demonstrates it.

Leave a Reply

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