How to create a button that redirects to a random website

Have you ever heard of The Useless Web? The Useless Web is a website with one very simple purpose: to redirect visitors to a random website. Simple but cool right? I liked the idea so much that I wanted to create something similar for my own website.

Wouter
2 min readMar 6, 2020

The idea

The idea is to let the user click a button causing him to be redirected to a random but funny website.

How to

I’m lazy. So we ain’t going to use complicated technologies to set this up. We are going to use PHP because this was the easiest to setup and the fastest to place online.

And no.. I don’t care whether you like PHP or not. I’m a .NET developer too.. But you should be open to new approaches and other programming languages.

Things you’ll need:

  • A webhost or server to host the files. In this tutorial we’re gonna use PHP
  • A TXT file (you read that right)
  • A list of random websites

How it’s going to work:

  • A button is going to be placed on our website.
  • When the user clicks it he is going to be redirected to our PHP file.
  • The PHP file is going to redirect the user to a random website.

The code

Step one: create a TXT file, each line should contain one random website. The file should be in the same directory as the PHP file.

Your setup should somewhat look like this:

Step two: fetch the list of random websites from our text file and put it inside of an array.

$addresses = explode(“\n”, file_get_contents(‘random-sites.txt’));

step three: retrieve a random element from the array.

$size = count($addresses);
$randomIndex = rand(0, $size — 1);
$randomUrl = $addresses[$randomIndex];

step four: redirect the user to the selected website

header(‘Location: ‘ . urldecode($randomUrl), true, 303);

And that’s it!

Now when our users navigate to the random.php file they will be redirected to a random website from the list!

See it in action here.

--

--