The full source code is available on GitHub. I wanted to give readers a chance to understand it and maybe make their own.
The generator can be broken down into two parts: the server side, which fetches the data from MetaReddit, and the client side, which creates a url and redirects the user.
1) server side - fetch.php
I wrote the code in PHP. We want to get the data from MetaReddit and
Contents of fetch.php:
<? $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://metareddit.com/reddits/biggest/cloud"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); echo curl_exec($ch); curl_close($ch); ?>
We start by opening a cURL session with
curl_init. Then, we set the URL to Metareddit's cloud.
We set the
CURLOPT_RETURNTRANSFER parameter to
1, so the contents of the page are returned as a string that we can
And finally we close the cURL session with
The next half of our generator needs to parse the contents of the MetaReddit page, create a URL, and redirect the user.
2) client side - index.html
We use the jQuery library. There are plenty of pros and cons to using Google's CDN; I generally do.
There are two JS functions for the generator:
init will populate a hidden element with our local list of subreddits - this is actually just the entire HTML source code of MetaReddit's cloud. We can get individual subreddit names using the
#invisibleHolder with the output of
fetch.php. This isn't instantaneous, so every 3 seconds we check whether the output has been received. Once it is,
run is called.
The output returns the links with your domain at the beginning. So we get all of the
a tags with the class
.subreddit and return the
href contents without
SERVER_NAME at the beginning - these formatted strings become the elements of the array
http://www.reddit.com/subreddit1+subreddit2+subreddit3... and so on. The user is redirected to the generated link.
And the body tag:
And that's it!
fetch.php gets the HTML source code of MetaReddit's cloud.
index.html gets the subreddit names from that content and redirects the user to a random link. You can check out the working demo.
The same PHP can be used to make a simple proxy. Many sites, however, restrict you from fetching content in this way with their
Please let me know what you think. Any suggestions, questions, or comments are totally welcome!