Random Text Generator

Display random quotes, tips, fortunes, or any text snippets on your website with each page load.

Perl SSI 1990s Classic Lightweight

Quick Info

  • Language: Perl 5
  • Requires: SSI Support
  • Data: Plain text file
  • License: Free for use
  • Era: 1995-2000

Overview

Random Text Generator reads from a text file containing multiple entries separated by delimiters and displays one entry at random each time the page loads. This simple but effective technique was popular for adding dynamic content to otherwise static HTML pages.

What It Does
  • Reads entries from a plain text file
  • Selects one entry randomly on each request
  • Outputs selected text to the page
  • No database required
How It Works
  • Text file contains entries separated by %%
  • Script parses file and counts entries
  • Random number selects one entry
  • Output via Server Side Includes (SSI)

Popular Use Cases

Quote of the Day

Display inspirational quotes, famous sayings, or proverbs that change with each visit.

Tips & Facts

Share random tips, fun facts, or educational snippets to engage visitors.

Fortune Cookies

Recreate the Unix "fortune" command on your website with custom messages.

Announcements

Rotate promotional messages, news items, or announcements on your homepage.

Greetings

Show different welcome messages or greetings to make your site feel more personal.

Jokes

Display random jokes, puns, or humorous content to entertain visitors.

How It Works

Data File Format

Create a plain text file with entries separated by the %% delimiter. Each entry can be a single line or multiple lines:

Single Line Entries
The journey of a thousand miles begins with a single step.
%%
To be or not to be, that is the question.
%%
Knowledge is power.
%%
Fortune favors the bold.
Multi-Line Entries
<blockquote>
  <p>Stay hungry, stay foolish.</p>
  <footer>Steve Jobs</footer>
</blockquote>
%%
<blockquote>
  <p>Be the change you wish to see.</p>
  <footer>Mahatma Gandhi</footer>
</blockquote>
Processing Flow
Browser Request
Apache SSI
rand_text.pl
quotes.txt
Step Component Action
1 Browser Requests a .shtml page from the server
2 Apache Processes SSI directive: <!--#exec cgi="..."-->
3 rand_text.pl Opens and reads the data file (e.g., quotes.txt)
4 rand_text.pl Splits content by %% delimiter into array
5 rand_text.pl Generates random index: rand(@entries)
6 Apache Inserts script output into the HTML response

Code Examples

Using SSI in Your HTML Page
<!-- In your .shtml file -->
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <h1>Welcome!</h1>

    <div class="quote-box">
        <h3>Quote of the Day</h3>
        <!--#exec cgi="/cgi-bin/rand_text.pl"-->
    </div>

    <!-- Or with custom data file -->
    <div class="tip-box">
        <h3>Today's Tip</h3>
        <!--#exec cgi="/cgi-bin/rand_text.pl?file=tips.txt"-->
    </div>
</body>
</html>
Note: SSI requires Apache with mod_include enabled and .shtml file extension (or Options +Includes for all HTML files).
Original Perl Script (rand_text.pl)
#!/usr/bin/perl
# rand_text.pl - Random Text Generator
# Classic CGI Script Archive

# Configuration
$datafile = "/path/to/quotes.txt";
$delimiter = "%%";

# Seed random number generator
srand(time ^ $$);

# Read and parse the data file
open(FILE, $datafile) || die "Cannot open $datafile: $!";
$/ = undef;  # Slurp mode
$content = <FILE>;
close(FILE);

# Split into entries
@entries = split(/$delimiter/, $content);

# Remove empty entries
@entries = grep { /\S/ } @entries;

# Select random entry
$random_index = int(rand(@entries));
$selected = $entries[$random_index];

# Clean up whitespace
$selected =~ s/^\s+//;
$selected =~ s/\s+$//;

# Output
print "Content-type: text/html\n\n";
print $selected;
PHP Equivalent
<?php
/**
 * Random Text Generator - PHP Version
 * Display a random entry from a text file
 */

$datafile = 'quotes.txt';
$delimiter = '%%';

// Read file content
$content = file_get_contents($datafile);

if ($content === false) {
    echo "Error reading file";
    exit;
}

// Split into entries
$entries = explode($delimiter, $content);

// Filter empty entries
$entries = array_filter($entries, function($entry) {
    return trim($entry) !== '';
});

// Re-index array
$entries = array_values($entries);

// Select random entry
if (count($entries) > 0) {
    $random = $entries[array_rand($entries)];
    echo trim($random);
} else {
    echo "No entries found";
}
?>

<!-- Usage in HTML -->
<div class="quote">
    <?php include 'rand_text.php'; ?>
</div>
Modern JavaScript (Client-Side)
// quotes.json
{
    "quotes": [
        {
            "text": "The journey of a thousand miles begins with a single step.",
            "author": "Lao Tzu"
        },
        {
            "text": "To be or not to be, that is the question.",
            "author": "William Shakespeare"
        },
        {
            "text": "Knowledge is power.",
            "author": "Francis Bacon"
        }
    ]
}

// JavaScript to display random quote
async function displayRandomQuote() {
    try {
        const response = await fetch('/data/quotes.json');
        const data = await response.json();

        const quotes = data.quotes;
        const randomIndex = Math.floor(Math.random() * quotes.length);
        const quote = quotes[randomIndex];

        document.getElementById('quote-text').textContent = quote.text;
        document.getElementById('quote-author').textContent = `— ${quote.author}`;
    } catch (error) {
        console.error('Error loading quotes:', error);
    }
}

// Run on page load
document.addEventListener('DOMContentLoaded', displayRandomQuote);

// HTML
// <blockquote id="quote-text"></blockquote>
// <cite id="quote-author"></cite>
// <button onclick="displayRandomQuote()">New Quote</button>

Historical Context

The Unix Fortune Program

The concept of displaying random text on websites originated from the Unix fortune program, which has been part of Unix systems since the 1970s. When you logged into a Unix terminal, you might see a random quote, joke, or saying.

$ fortune
"The generation of random numbers is too important to be left to chance."
                                        -- Robert R. Coveyou

The Random Text Generator brought this functionality to the web, allowing webmasters to add dynamic, changing content without databases or complex server configurations.

Server Side Includes (SSI) Era

Before PHP became widespread, SSI was the primary way to add dynamic content to static HTML pages:

SSI Directive Purpose
<!--#include file="..."--> Include another file
<!--#exec cgi="..."--> Execute a CGI script
<!--#echo var="..."--> Display server variable
<!--#flastmod file="..."--> Last modification date
Did You Know?

The Unix fortune database contains over 20,000 quotes covering everything from literature to computer science jokes!

Fun Fact

Many Unix users added fortune to their .bashrc file so they'd see a random quote every time they opened a terminal!

Timeline
  • 1970s: Unix fortune created
  • 1993: Apache SSI introduced
  • 1995: CGI scripts popularized
  • 1998: PHP begins replacing SSI
  • 2010s: JavaScript takes over

Modern Alternatives (2024)

Today there are many ways to display random content, from simple JavaScript to dedicated quote APIs.

JavaScript Libraries & Widgets

Vanilla JavaScript
Free

Use native JavaScript with JSON data files. No libraries needed, full control over presentation.

  • Zero dependencies
  • Full customization
  • Works offline
  • No API limits
Quotable API
Free

Open-source REST API with 2000+ quotes. Returns random quotes with author attribution.

  • 2000+ curated quotes
  • Filter by author/tag
  • JSON responses
  • No API key needed
ZenQuotes API
Free Tier

Inspirational quotes API with thousands of curated quotes from famous people.

  • 5 requests/30 seconds (free)
  • Inspirational focus
  • Image quotes available
  • Author data included

WordPress Plugins

Jetonner Quotes

Display random quotes with shortcodes and widgets.

Free
Jetkoo Quote Rotator

Animated quote display with transitions.

Free + Pro
Jetveo Testimonials

Customer testimonials with random display.

Free + Pro
Daily Quote Widget

Sidebar widget with daily changing quotes.

Free

Comparison: Then vs Now

Feature Perl/SSI (1990s) Modern Solutions (2024)
Data Source Plain text file with delimiters JSON, API, database, CMS
Rendering Server-side only Client-side or server-side
Caching None (new request each time) Browser cache, CDN, service workers
Animation None CSS transitions, fade effects
Refresh Page reload required AJAX, instant updates
Management Edit text file manually Admin UI, CMS integration
Metadata Plain text only Author, date, category, tags

Download

Random Text Generator is available in several archive formats:

  • rand_text.tar.gz Unix/Linux
  • rand_text.zip Windows
Package Contents
  • rand_text.pl - Main CGI script
  • quotes.txt - Sample data file
  • README - Installation instructions

Frequently Asked Questions

A Random Text Generator is a script that reads multiple text entries from a data file and displays one randomly selected entry each time a web page is loaded. Popular uses include displaying quotes of the day, random tips, fortune cookie messages, or rotating announcements. The classic implementation uses a Perl CGI script with Server Side Includes (SSI).

Create a plain text file with entries separated by the %% delimiter. Each entry can be a single line or span multiple lines. For example:
First quote here.
%%
Second quote here.
%%
Third quote with
multiple lines.
The script will read this file, split it by the %% delimiter, and randomly select one entry to display.

Yes! The script outputs the selected entry as-is, so you can include HTML formatting like <b>, <i>, <blockquote>, or even entire HTML structures. This allows for rich formatting of quotes with attribution, images, or styling.

Server Side Includes (SSI) is an Apache web server feature that processes special directives in HTML files before sending them to the browser. The <!--#exec cgi="..."--> directive executes a CGI script and includes its output. SSI requires Apache's mod_include module and typically uses .shtml file extensions. For modern websites, PHP or JavaScript are more common alternatives.

The original SSI/Perl approach requires a page reload. For dynamic quote updates without reloading, use JavaScript with JSON data or a quote API. You can load all quotes once and use JavaScript to randomly select and display them, or make AJAX calls to a server endpoint. This provides a better user experience with instant updates.

Modern approaches include: (1) JavaScript with JSON - store quotes in a JSON file and use client-side JavaScript to randomly select and display; (2) Quote APIs - use services like Quotable or ZenQuotes that provide random quotes via REST APIs; (3) CMS plugins - WordPress plugins like Quote Rotator; (4) PHP - simple server-side script similar to the original Perl but with modern PHP.

Related Scripts

Back to Scripts