You're here: Home / PHP /

Displaying Random Image in Your Page

Displaying a random image in your page is cool & fun. It's also useful if you want to display random banners or such. Here it is:

<?php
/**
 * random_img.php :
 * This script selects a random image from a specified
 * directory and outputs the image to browser.
 */

/* output selected image to browser */
function out2browser($filename) 
{
    list($width, $height, $type) = getimagesize($filename);
    
    switch($type) {
        case IMAGETYPE_PNG:
            $img = imagecreatefrompng($filename);
            header("Content-type: image/png");
            imagepng($img);
            break;
        case IMAGETYPE_GIF:
            $img = imagecreatefromgif($filename);
            header("Content-type: image/gif");
            imagegif($img);
            break;
        case IMAGETYPE_JPEG:
            $img = imagecreatefromjpeg($filename);
            header("Content-type: image/jpeg");
            imagejpeg($img);
            break;
    }
}

/* change to your images directory */
$imgpath = "C:/www/img/avatar";
$images  = array();

/* list images */
$files = scandir($imgpath);

foreach($files as $file) {
    /* select only gif, jpg and png images */
    $ext = substr($file, -4);
    if ($ext == '.gif' || $ext == '.jpg' || $ext == '.png') {
        $images[] = $file;
    }
}

/* select random image */
$val = rand(0, count($images) - 1);
$img = $images[$val];

out2browser("$imgpath/$img");
?>

The script above will display a random image from the specified directory. Use the script above in your <img> tag like this:

<img src="random_img.php" border="0" alt="my random image" />

Wanna see this script in action? Take a look at my avatar at the right side. The image is randomly selected every day. Come visit my site tomorrow and you'll see different avatar there.

Keywords: display random image, random banner, random avatar

Share:  del.icio.us logo Save to del.icio.us  digg logo Digg this!

comment.gifAdd your comment

(required, will not be published) (optional)