Posted December 2024
Keystroke to Go to Random Web Page
Most pages on THE LAB have event listeners set up so that if you press Alt + R you will be taken to a random page on the site. This is a fun way to explore the site. It's a simple bit of JavaScript that listens for the keydown event, and if the Alt key and the R key are pressed, it will take you to a random page.
I created this for my site "Smorgasborg" which is a kind of "junk drawer" offshoot from my personal site.
Large websites can be cumbersome to explore, particularly sites with a lot of pages.
It's also useful for me to spot-check changes to a website as a hidden feature.
JavaScript Code to listen for keystrokes
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('keydown', function(event) {
console.log(event);
if (event.altKey && event.keyCode === 82) {
// if we are in frames, go to the top
if (window.top !== window.self) {
window.top.location = '/random.php';
}
window.location = '/random.php';
}
});
});
PHP Code inside random.php
<?php
require_once '../loader.php';
$directories = glob('*', GLOB_ONLYDIR);
$urls = [];
$urls[] = '/';
// for a small filesystem based site this is okay,
// but for a larger site you'd want to cache the
// list of directories
foreach ($directories as $directory) {
$just_slug = $directory;
// My convention is to have a directory with the same name as the slug
// Directories without that convention would be ignored,
// To implement this you could also check for index.html or index.php.
// Whatever indicates to the script what a valid page would be
$file = "$directory/$just_slug.php";
if (file_exists($file)) {
$urls[] = "/$just_slug/";
}
}
$link = rand(0, count($urls) - 1);
$url = $urls[$link];
// We want to be able to run this from the command line
if (php_sapi_name() != 'cli') {
header('Location: ' . $url);
} else {
echo $url . "\n";
}