Random Image Displayer

Rotating Banner and Image Rotation Script

Random Image Displayer allows you to set up a list of images and randomly display them as inline images or background images. No Server Side Includes required - just point an IMG tag to the script. Perfect for rotating banners, advertisements, and artwork galleries.

Free Download
Version 1.0
Perl CGI

Live Demo

Random Image (JavaScript Demo)
Click to show random image

JavaScript recreation - original would serve actual images

How to Use

Simply use the script URL as your image source:

<img src="/cgi-bin/rand_image.pl">

The script outputs image data directly, so browsers display it like any normal image.

Overview

Random Image Displayer is a simple Perl CGI script that randomly selects and outputs an image from a configured list. Unlike the SSI version, this script works with a standard IMG tag and doesn't require Server Side Includes to be enabled on your server.

How It Works

When the script is called via an IMG tag, it randomly selects an image from its configuration, reads the image file, and outputs it with the correct Content-Type header. The browser receives raw image data, just like from a static image file.

Package Contents
File Description
rand_image.pl Main Perl script that selects and outputs random images
README Installation instructions and configuration guide
Common Uses
  • Rotating banner advertisements
  • Random artwork/photo display
  • Rotating sponsor logos
  • Random background images
  • Quote of the day images
  • Seasonal/holiday banners

Features

Random Selection

Truly random image selection from your configured list with each page load.

No SSI Required

Works with standard IMG tags - no need to enable Server Side Includes on your server.

Multiple Formats

Supports GIF, JPEG, and PNG image formats with automatic content type detection.

Background Support

Can be used for random background images in addition to inline images.

Easy Configuration

Simple array-based configuration - just list the paths to your images.

Lightweight

Minimal server overhead - just reads and outputs image data.

Standard vs SSI Version

Feature Random Image Displayer SSI Random Image
Server Side Includes Required No Yes
Alt Text Support No Yes
Width/Height Attributes No Yes
Associated Links No Yes
Usage Simplicity Very Simple Moderate
Hosting Compatibility Most hosts SSI-enabled only

Recommendation: Use the standard version for simple banner rotation. Use the SSI version if you need clickable images with proper accessibility attributes.

Installation

  1. Upload the Script
    Upload rand_image.pl to your cgi-bin directory.
  2. Configure Perl Path
    Edit the first line to point to your Perl interpreter (usually #!/usr/bin/perl).
  3. Upload Your Images
    Upload the images you want to rotate to a web-accessible directory.
  4. Configure Image Paths
    Edit the @images array in the script with the full filesystem paths to your images.
  5. Set Permissions
    Set the script permissions to 755: chmod 755 rand_image.pl
  6. Add to Your Pages
    Use an IMG tag pointing to the script: <img src="/cgi-bin/rand_image.pl">

Code Examples

Perl Implementation
#!/usr/bin/perl
use strict;
use warnings;

# Configuration - list your images here
my @images = (
    '/var/www/html/images/banners/banner1.gif',
    '/var/www/html/images/banners/banner2.gif',
    '/var/www/html/images/banners/banner3.jpg',
    '/var/www/html/images/banners/banner4.png',
);

# Select random image
my $image = $images[int(rand(@images))];

# Determine content type
my $content_type = 'image/gif';  # default
if ($image =~ /\.jpe?g$/i) {
    $content_type = 'image/jpeg';
} elsif ($image =~ /\.png$/i) {
    $content_type = 'image/png';
} elsif ($image =~ /\.gif$/i) {
    $content_type = 'image/gif';
} elsif ($image =~ /\.webp$/i) {
    $content_type = 'image/webp';
}

# Output headers
print "Content-type: $content_type\n";
print "Cache-Control: no-cache, no-store, must-revalidate\n";
print "Pragma: no-cache\n";
print "Expires: 0\n\n";

# Output image data
if (open(my $fh, '<:raw', $image)) {
    local $/;
    print <$fh>;
    close($fh);
} else {
    # Error handling - could output a default image
    warn "Cannot open $image: $!";
}

exit 0;
PHP Implementation
<?php
/**
 * Random Image Displayer - PHP Version
 */

// Configuration - list your images here
$images = [
    '/var/www/html/images/banners/banner1.gif',
    '/var/www/html/images/banners/banner2.gif',
    '/var/www/html/images/banners/banner3.jpg',
    '/var/www/html/images/banners/banner4.png',
];

// Select random image
$image = $images[array_rand($images)];

// Check if file exists
if (!file_exists($image)) {
    http_response_code(404);
    exit;
}

// Determine content type
$extension = strtolower(pathinfo($image, PATHINFO_EXTENSION));
$content_types = [
    'gif'  => 'image/gif',
    'jpg'  => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png'  => 'image/png',
    'webp' => 'image/webp',
    'svg'  => 'image/svg+xml',
];

$content_type = $content_types[$extension] ?? 'application/octet-stream';

// Prevent caching for true randomness
header('Content-Type: ' . $content_type);
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Content-Length: ' . filesize($image));

// Output image
readfile($image);
exit;
?>
PHP with Weighted Rotation
<?php
/**
 * Random Image with Weighted Probability
 * Useful for ad rotation where some ads should appear more often
 */

$images = [
    ['path' => '/images/sponsor_platinum.png', 'weight' => 50],
    ['path' => '/images/sponsor_gold.png', 'weight' => 30],
    ['path' => '/images/sponsor_silver.png', 'weight' => 15],
    ['path' => '/images/sponsor_bronze.png', 'weight' => 5],
];

function weightedRandom($items) {
    $totalWeight = array_sum(array_column($items, 'weight'));
    $random = mt_rand(1, $totalWeight);

    $current = 0;
    foreach ($items as $item) {
        $current += $item['weight'];
        if ($random <= $current) {
            return $item['path'];
        }
    }
    return $items[0]['path'];
}

$selectedImage = weightedRandom($images);

// Output image (same as above)
// ...
?>
JavaScript Implementation (Recommended)
/**
 * Random Image Displayer - JavaScript Version
 * Client-side solution with no server requests per image
 */

class RandomImage {
    constructor(element, images, options = {}) {
        this.element = typeof element === 'string'
            ? document.querySelector(element)
            : element;

        this.images = images;
        this.options = {
            preload: true,
            fadeTransition: true,
            transitionDuration: 300,
            interval: 0,  // 0 = no auto-rotation
            ...options
        };

        this.currentIndex = -1;
        this.preloadedImages = [];

        this.init();
    }

    init() {
        if (this.options.preload) {
            this.preloadImages();
        }

        this.showRandom();

        if (this.options.interval > 0) {
            setInterval(() => this.showRandom(), this.options.interval);
        }
    }

    preloadImages() {
        this.images.forEach(src => {
            const img = new Image();
            img.src = src;
            this.preloadedImages.push(img);
        });
    }

    showRandom() {
        // Ensure we don't show the same image twice in a row
        let newIndex;
        do {
            newIndex = Math.floor(Math.random() * this.images.length);
        } while (newIndex === this.currentIndex && this.images.length > 1);

        this.currentIndex = newIndex;
        const src = this.images[newIndex];

        if (this.options.fadeTransition) {
            this.fadeTransition(src);
        } else {
            this.element.src = src;
        }
    }

    fadeTransition(src) {
        this.element.style.transition = `opacity ${this.options.transitionDuration}ms`;
        this.element.style.opacity = '0';

        setTimeout(() => {
            this.element.src = src;
            this.element.style.opacity = '1';
        }, this.options.transitionDuration);
    }

    // Manual control methods
    next() {
        this.currentIndex = (this.currentIndex + 1) % this.images.length;
        this.showImage(this.currentIndex);
    }

    prev() {
        this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
        this.showImage(this.currentIndex);
    }

    showImage(index) {
        const src = this.images[index];
        if (this.options.fadeTransition) {
            this.fadeTransition(src);
        } else {
            this.element.src = src;
        }
    }
}

// Usage examples:

// Basic usage
const banner = new RandomImage('#banner-image', [
    '/images/banner1.jpg',
    '/images/banner2.jpg',
    '/images/banner3.jpg'
]);

// With auto-rotation
const slideshow = new RandomImage('#slideshow', [
    '/images/slide1.jpg',
    '/images/slide2.jpg',
    '/images/slide3.jpg'
], {
    interval: 5000,  // Rotate every 5 seconds
    fadeTransition: true,
    transitionDuration: 500
});

// Background image rotation
class RandomBackground {
    constructor(element, images, options = {}) {
        this.element = document.querySelector(element);
        this.images = images;
        this.options = { interval: 10000, ...options };

        this.showRandom();
        if (this.options.interval > 0) {
            setInterval(() => this.showRandom(), this.options.interval);
        }
    }

    showRandom() {
        const src = this.images[Math.floor(Math.random() * this.images.length)];
        this.element.style.backgroundImage = `url('${src}')`;
    }
}

new RandomBackground('body', [
    '/images/bg1.jpg',
    '/images/bg2.jpg',
    '/images/bg3.jpg'
], { interval: 30000 });
HTML Usage Examples
<!-- Basic usage with CGI script -->
<img src="/cgi-bin/rand_image.pl" alt="Random Banner">

<!-- As a background image (inline style) -->
<body background="/cgi-bin/rand_image.pl">

<!-- Multiple random images on same page -->
<img src="/cgi-bin/rand_image.pl?set=banners" alt="Banner">
<img src="/cgi-bin/rand_image.pl?set=sponsors" alt="Sponsor">

<!-- Modern JavaScript approach (recommended) -->
<img id="random-banner" src="" alt="Random Banner">

<script>
const banners = [
    '/images/banners/summer-sale.jpg',
    '/images/banners/new-arrivals.jpg',
    '/images/banners/free-shipping.jpg'
];

document.getElementById('random-banner').src =
    banners[Math.floor(Math.random() * banners.length)];
</script>

<!-- Bootstrap carousel with random start -->
<div id="carouselExample" class="carousel slide" data-bs-ride="carousel">
    <div class="carousel-inner">
        <div class="carousel-item active">
            <img src="/images/slide1.jpg" class="d-block w-100" alt="Slide 1">
        </div>
        <div class="carousel-item">
            <img src="/images/slide2.jpg" class="d-block w-100" alt="Slide 2">
        </div>
        <div class="carousel-item">
            <img src="/images/slide3.jpg" class="d-block w-100" alt="Slide 3">
        </div>
    </div>
</div>

<script>
// Start carousel at random slide
const carousel = document.querySelector('#carouselExample');
const items = carousel.querySelectorAll('.carousel-item');
const randomStart = Math.floor(Math.random() * items.length);

items.forEach((item, index) => {
    item.classList.toggle('active', index === randomStart);
});
</script>

Download

Compressed Archives
  • image.tar.gz 2.4 KB
  • image.zip 2.6 KB
  • image.tar.Z 3.4 KB
  • image.tar 10.3 KB
Individual Files
  • rand_image.pl

    Main Perl script that randomly selects and outputs images

  • README

    Installation instructions and configuration guide

Frequently Asked Questions

This basic version doesn't support links or alt text because it outputs raw image data. If you need these features, use the SSI Random Image Displayer which outputs a complete IMG tag with configurable attributes, or use JavaScript to handle the image display with proper attributes.

Browsers cache images by URL. Since the script URL doesn't change, the browser may cache the first image. Add cache-control headers to prevent this (shown in code examples), or append a random query string: <img src="/cgi-bin/rand_image.pl?t=1766154611"> to force a new request each time.

Yes, you can modify the script to accept a query parameter specifying which image set to use. For example: /cgi-bin/rand_image.pl?set=banners and /cgi-bin/rand_image.pl?set=sponsors. The script would then read from different configuration arrays based on the parameter.

Add logging to the script by writing to a log file or database each time an image is selected. This is useful for tracking ad impressions. Include a timestamp, image path, and optionally the referring page. For click tracking, wrap the image in a tracking link that redirects to the destination.

Yes, implement weighted random selection (see the PHP example in Code Examples). Assign a weight to each image and select based on the cumulative weight. This is useful for ad rotation where premium sponsors should appear more frequently than others.

The CGI version has overhead from starting the Perl interpreter for each request. For high-traffic sites, consider: (1) Using JavaScript for client-side random selection, (2) Switching to a compiled solution, (3) Using mod_perl to keep Perl in memory, or (4) Pre-generating random image selections and serving static files.

Yes, JavaScript is the preferred method today. It requires no server resources per image load, supports smooth transitions, allows preloading, and works with any hosting. See the JavaScript examples above. For ad serving specifically, consider Google AdSense or dedicated ad platforms with proper tracking and targeting.

CGI random images work well in emails since the image is fetched when the email is opened. Each recipient sees a potentially different image. Note that some email clients block external images, and JavaScript won't work in emails. This is actually one use case where server-side random images remain relevant.