*nao | notanorange


PHP: Random Images

A little while ago, I was asked to “sort out a website” for a friend of mine. A big part of this was the randomly picked images that sit behind the content.

While writing the few lines of PHP to accomplish this, I decided it would be for the best if Ben – who will be the first to admit he’s not very code-savvy – didn’t have to touch any code if he wanted to change the images.

Here’s how I did it:

$dir = "images"; // the directory the images are in
// get all the filenames into an array
if ($dh = opendir($dir)) {
    $count = 0;
    while (false !== ($file = readdir($dh))) {
        $file = removeExtension($file);
        if ($file == "." || $file == "") {
            // do nothing
        } else {
            $imageList[$count] = $file;
            $count++;
        }
    }
    closedir($dh);
}
// remove file extensions
function removeExtension($strName) {
    $ext = strrchr($strName, '.');
    if($ext !== false) {
        $strName = substr($strName, 0, -strlen($ext));
    }
    return $strName;
}
$imgCount = sizeof($imageList) - 1;
$imgNum = rand(0,$imgCount);


Then, wherever the image is needed:

<img src="<?php echo $dir ."/". $imageList[$imgNum]; ?>.jpg" alt="" />


And that’s that. All you need to do is drop any images you want to use into that folder.

Obviously, after one look at that code you’ll notice that the images need to be JPGs, but that wasn’t an issue with Ben’s images as they are all large sized JPGs. I’ll probably revise this snippet at some point, but in the mean time, head over to Ben’s site and give it a few refreshes to see it in action (just try not to rape too much of his bandwidth).

2 Responses to “PHP: Random Images”

  1. [...] This post was mentioned on Twitter by Neil Kemp. Neil Kemp said: Keeping to my "at least 1 post a month" resolution (only just). http://bit.ly/9FpmD4 Quick post about random images with PHP. [...]

  2. ahhhh, we were talking about this earlier. Nice work.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

April 30, 2010
2 Comments

Posted in: Web.