Random Images

PHP Best Practices

A fast method for displaying random images from a directory

Date : 2006-02-21
Random Images

Often times it is useful to be able to show a random image on a page. This could be used for ads, for displaying special features or various other random information.

Today I'm going to show you how to write an easy php script that will peruse a directory that you give it for images and then display those same images with a link to a location that you define.

First we need to create a directory to house our images. I put mine in /images/random.

Next we need a function to peruse the given directory:

function DisplayRandomImage() {

  $dir = "/images/random/";
  if ($photo_files = @opendir($dir)) {
    $photoCount = 0;
    while(($file = readdir($photo_files)) !== false) {
      if(!preg_match("/^./", $file)){
        $photoCount ++;
        $filename[] = $file;

  $which = rand(1,$photoCount) - 1;
  $filename = $filename[$which];
  $locationid = ereg_replace('.gif','',$filename);

  echo "<a href='http://www.mysite.com/articles/$locationid.html'><img src='../images/random/$filename'></a>"; 

So first we define the directory that we want the script to look inside for images using the $dir variable.

Next we try and open the directory and make sure there is at least 1 photo in it. If there is, then its gets read into an array called $photoCount.

Finally we use the $which var along with rand function to randomly choose an image from the array ($photoCount). $filename then stores the actual name of the file and then we use $locationid to trim the file so that we can use it in a URL.

The final line builds the URL and displays the image. Note the form the URL takes here. You will need to make sure that for each image that is in the random directory that there actually exists an html file that corresponds to the image files name.

Calling this function is as simple as adding the line:

<? DisplayRandomImage; ?>

At an appropriate location in your code.

Comments :

No comments yet
  • Search For Articles