Random Link Generator

Random URL Redirect and Site Discovery Script

Random Link Generator redirects visitors to a random URL from your configured database. When clicked, users are taken to a randomly selected site from your list. Perfect for link rotators, random site discovery, and partner link distribution.

Free Download
Version 1.0
Perl CGI

Overview

Random Link Generator allows you to create a "random site" link that, when clicked, redirects visitors to a randomly selected URL from your database. The URLs are stored in a simple text file, making it easy to add or remove links.

How It Works

When a visitor clicks the link to the script, it reads the URL database file, randomly selects one URL, and sends an HTTP redirect to that URL. The visitor is instantly taken to the random destination.

Package Contents
File Description
rand_link.pl Main Perl script that performs the random redirect
rand_link.html Sample HTML page showing how to call the script
rand_log Optional log file for tracking usage
README Installation instructions and configuration guide
Common Uses
  • "Random Site" buttons
  • Web ring navigation
  • Partner/affiliate link rotation
  • Random resource discovery
  • A/B testing redirects
  • Load balancing (basic)

Features

True Random Selection

Each click selects a truly random URL from your database with equal probability.

Simple Database

URLs stored in a plain text file, one per line. Easy to edit and maintain.

Optional Logging

Track which URLs are accessed and when for analytics and monitoring.

Fast Redirect

Uses HTTP 302 redirect for instant redirection to the destination.

FFA Integration

Works with Free For All Link pages for automatic database updates.

Easy Configuration

Minimal setup required - just configure the database file path.

Database Format

The URL database is a simple text file with one URL per line:

links.txt - Example Database
https://example1.com/
https://example2.com/path/to/page.html
https://example3.org/
http://legacy-site.com/old-page.html
https://partner-site.net/landing
Important: Ensure each URL is on its own line with no extra whitespace. Include the full URL with protocol (http:// or https://).

Installation

  1. Upload the Script
    Upload rand_link.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. Create URL Database
    Create a text file with your URLs, one per line, in a web-accessible location.
  4. Configure Database Path
    Edit the script to set the $linkfile variable to the path of your URL database.
  5. Set Permissions
    Set script permissions to 755: chmod 755 rand_link.pl
  6. Create Link to Script
    Add <a href="/cgi-bin/rand_link.pl">Random Site</a> to your pages.

Code Examples

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

# Configuration
my $linkfile = '/var/www/data/links.txt';
my $logfile  = '/var/www/logs/rand_link.log';
my $enable_logging = 1;

# Read links from file
open(my $fh, '<', $linkfile) or die "Cannot open $linkfile: $!";
my @links = grep { /^https?:\/\// } map { chomp; $_ } <$fh>;
close($fh);

# Check if we have any links
if (!@links) {
    print "Content-type: text/html\n\n";
    print "No links available.";
    exit;
}

# Select random link
my $url = $links[int(rand(@links))];

# Log the access (optional)
if ($enable_logging && $logfile) {
    if (open(my $log, '>>', $logfile)) {
        my $time = localtime();
        my $ip = $ENV{REMOTE_ADDR} || 'unknown';
        my $referer = $ENV{HTTP_REFERER} || 'direct';
        print $log "$time | $ip | $referer | $url\n";
        close($log);
    }
}

# Redirect to the random URL
print "Status: 302 Found\n";
print "Location: $url\n\n";

exit 0;
PHP Implementation
<?php
/**
 * Random Link Generator - PHP Version
 */

// Configuration
$linkfile = '/var/www/data/links.txt';
$logfile = '/var/www/logs/rand_link.log';
$enable_logging = true;

// Read links from file
$links = file($linkfile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

if ($links === false || empty($links)) {
    die('No links available.');
}

// Filter to valid URLs only
$links = array_filter($links, function($url) {
    return filter_var($url, FILTER_VALIDATE_URL);
});

if (empty($links)) {
    die('No valid links available.');
}

// Select random link
$url = $links[array_rand($links)];

// Log the access (optional)
if ($enable_logging && $logfile) {
    $time = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $referer = $_SERVER['HTTP_REFERER'] ?? 'direct';
    $log_entry = "$time | $ip | $referer | $url\n";
    file_put_contents($logfile, $log_entry, FILE_APPEND | LOCK_EX);
}

// Redirect to the random URL
header('Location: ' . $url, true, 302);
exit;
?>
PHP with Weighted Links
<?php
/**
 * Weighted Random Link Generator
 * Links with higher weights appear more often
 */

// Format: URL|weight
$links = [
    'https://premium-partner.com/' => 50,
    'https://gold-partner.com/' => 30,
    'https://silver-partner.com/' => 15,
    'https://bronze-partner.com/' => 5,
];

function weightedRandom($items) {
    $total = array_sum($items);
    $rand = mt_rand(1, $total);
    $current = 0;

    foreach ($items as $url => $weight) {
        $current += $weight;
        if ($rand <= $current) {
            return $url;
        }
    }

    return array_key_first($items);
}

$url = weightedRandom($links);
header('Location: ' . $url, true, 302);
exit;
?>
JavaScript Implementation
/**
 * Random Link Generator - JavaScript Version
 * Client-side random redirect with no server required
 */

class RandomLinkGenerator {
    constructor(links, options = {}) {
        this.links = links;
        this.options = {
            openInNewTab: true,
            trackClicks: false,
            ...options
        };
    }

    getRandomLink() {
        return this.links[Math.floor(Math.random() * this.links.length)];
    }

    redirect() {
        const url = this.getRandomLink();

        if (this.options.trackClicks) {
            this.trackClick(url);
        }

        if (this.options.openInNewTab) {
            window.open(url, '_blank', 'noopener,noreferrer');
        } else {
            window.location.href = url;
        }
    }

    trackClick(url) {
        // Send to analytics
        console.log('Random link clicked:', url);
        // navigator.sendBeacon('/track/click', JSON.stringify({ url: url }));
    }

    // Bind to a button/link element
    bindTo(selector) {
        const element = document.querySelector(selector);
        if (element) {
            element.addEventListener('click', (e) => {
                e.preventDefault();
                this.redirect();
            });
        }
    }
}

// Usage examples:

// Basic usage
const links = [
    'https://example1.com/',
    'https://example2.com/',
    'https://example3.com/',
    'https://example4.com/',
];

const randomizer = new RandomLinkGenerator(links);

// Bind to a button
randomizer.bindTo('#random-link-button');

// Or redirect immediately
// randomizer.redirect();

// With weighted links
class WeightedRandomLinks {
    constructor(weightedLinks) {
        this.links = weightedLinks;
        this.totalWeight = weightedLinks.reduce((sum, item) => sum + item.weight, 0);
    }

    getRandomLink() {
        let random = Math.random() * this.totalWeight;
        for (const item of this.links) {
            random -= item.weight;
            if (random <= 0) {
                return item.url;
            }
        }
        return this.links[0].url;
    }

    redirect() {
        window.location.href = this.getRandomLink();
    }
}

// Weighted usage
const weightedLinks = [
    { url: 'https://premium.com/', weight: 50 },
    { url: 'https://gold.com/', weight: 30 },
    { url: 'https://silver.com/', weight: 15 },
    { url: 'https://bronze.com/', weight: 5 },
];

const weighted = new WeightedRandomLinks(weightedLinks);

// HTML inline usage
// <a href="#" onclick="randomizer.redirect(); return false;">Random Site</a>
HTML Usage Examples
<!-- Basic link to CGI script -->
<a href="/cgi-bin/rand_link.pl">Visit a Random Site</a>

<!-- Styled button -->
<a href="/cgi-bin/rand_link.pl" class="btn btn-primary">
    <i class="bi bi-shuffle"></i> Random Site
</a>

<!-- Open in new tab -->
<a href="/cgi-bin/rand_link.pl" target="_blank" rel="noopener">
    Random Site (New Tab)
</a>

<!-- JavaScript approach (recommended for modern sites) -->
<button id="random-link-btn" class="btn btn-success">
    <i class="bi bi-shuffle"></i> Discover Random Site
</button>

<script>
const sites = [
    'https://example1.com/',
    'https://example2.com/',
    'https://example3.com/'
];

document.getElementById('random-link-btn').addEventListener('click', function() {
    const url = sites[Math.floor(Math.random() * sites.length)];
    window.open(url, '_blank', 'noopener');
});
</script>

<!-- Bootstrap card with random link feature -->
<div class="card">
    <div class="card-body text-center">
        <h5 class="card-title">Feeling Lucky?</h5>
        <p class="card-text">Discover a random site from our collection!</p>
        <a href="/cgi-bin/rand_link.pl" class="btn btn-lg btn-warning">
            <i class="bi bi-dice-5"></i> Take Me Somewhere Random
        </a>
    </div>
</div>

Extras

Utility scripts to help manage your link database:

Create URL Database

Converts Free For All link pages to Random Link database format. Extracts URLs from HTML and creates a clean link file.

make_list.pl
Bookmark Converter

Converts Netscape bookmark files to Random Link database format. Turn your bookmarks into a random discovery tool.

convert.pl

Download

Compressed Archives
  • rand_link.tar.gz 2.1 KB
  • rand_link.zip 2.6 KB
  • rand_link.tar.Z 2.9 KB
  • rand_link.tar 10.2 KB
Individual Files
  • rand_link.pl

    Main Perl script for random URL redirection

  • rand_link.html

    Sample HTML page with usage examples

  • rand_log

    Optional log file template for tracking

  • README

    Installation and configuration guide

Frequently Asked Questions

The link database is a simple text file with one URL per line. Each URL should be complete including the protocol (http:// or https://). Ensure there are no blank lines or extra whitespace. Example:
https://example1.com/
https://example2.com/page.html
https://example3.org/

Yes, the Extras section includes utility scripts: make_list.pl converts Free For All link pages to the database format, and convert.pl converts Netscape bookmark files. You can also use simple grep/sed commands or write a custom script to extract URLs from HTML.

The original script gives equal probability to all links. To implement weighted selection, you can either: (1) Add the same URL multiple times in the database (crude but simple), or (2) Modify the script to support a weighted format like URL|weight and implement weighted random selection (see code examples above).

Enable the logging feature by setting the log file path in the script. Each redirect will be logged with timestamp, visitor IP, referring page, and destination URL. For more advanced analytics, you can modify the script to insert data into a database or send events to Google Analytics.

Yes, modify the script to filter URLs based on your criteria before random selection. For example, you could exclude URLs that match certain patterns, implement time-based rotation (different URLs for weekdays vs weekends), or filter based on the referring page or visitor's country.

If you see the CGI URL in the browser's address bar briefly, the redirect is working correctly - that's just how HTTP redirects work. The browser requests the script, receives a redirect response, then requests the destination. For faster perception, ensure your server responds quickly (minimize script execution time).

Yes, JavaScript is often better for modern sites. Client-side random selection requires no server overhead, can include animations or preview information before redirecting, and works with any hosting. However, the server-side approach is still useful for tracking clicks without JavaScript and for simple installations.

Create a link checker script that reads your database and makes HEAD requests to each URL, logging any that return errors (404, 500, etc.) or timeouts. Run this periodically to keep your database clean. Many free online tools can also check links from a text file.