Link to a Random Page

By combining PHP with Javascript we can set up a link to a random page of our site. The PHP looks up the directory of all of the web pages on the site and randomly selects one to be displayed. It then reads the page source and extracts the first H1 or, if there isn't one, the page title. The Javascript code then takes over to display the link to that random page on your site like this:

If you refresh this page you will see that the above link changes to offer a different page from on this site.

The rather long piece of code that produces this link is as follows:

function omitFile($file) {
if (substr($file,strrpos($file,'.')+1) != 'htm') return true;
// add code here to omit any web pages you don't want included
return false;
function makeseed() {
list($usec, $sec) = explode(' ',microtime());
return (float) $sec + ((float) $usec * 1000000);
$entry = 0;
$page_handler = opendir("..");
while( $file = readdir($page_handler) )
if ( $file != "." && $file != ".." ) {
if (!omitFile($file))
$pageArray[$entry++] = $file;
$ent = mt_rand(0,$entry);
$file = fopen ("../$pageArray[$ent]", "r");
if ($file) {
$head = " ";
$title = " ";
while (!feof ($file)) {
$line = fgets ($file, 32768);
if ($head == " " && preg_match ('/h1 class="centre">(.*?)<\/h1/i', $line, $out)) {
$head = $out[1];
if ($head == " " && preg_match ('/h1>(.*?)<\/h1/i', $line, $out)) {
$head = $out[1];
if ($title == " " && preg_match ('/title>(.*?)<\/title/i', $line, $out)) {
$title = $out[1];
if ($head == " ") $head = $title;
if ($head == " ") $head = $pageArray[$ent];
echo "var pagename = '$pageArray[$ent]';\n";
echo "var pagetitle = '$head';\n";
document.writeln('<div class="centre"><a href="'+pagename+'">'+pagetitle+'<\/a></div>');

The code in this page to link to the above code is as follows:

<script type="text/javascript" src="inc/randpage.php">

The code is linked in as Javascript which means that it can be included in ordinary web pages and not just ones using PHP. Because of the php suffix on the filename instead of the more normal js the code in the script will run through the PHP pre-processor to generate the Javascript code to be passed with the web page. While this exact function may not be what you are looking for to add to your site the concepts demonstrated by this function with using PHP to read the directory and a selected file and then using Javascript to add the results into an ordinary HTML page may give you ideas on how you might achieve your desired effect by combining these two languages.

Note that the code to set up the link uses .. to refer to the parent directory because I have placed the script into the inc sub-directory. If you place the script in the same directory you want to select the link from you would code a single dot instead of the double ones in the opendir and fopen statements.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow