PHP URL Rotator

With a URL Rotator you can advertise one URL, and spread the traffic over multiple sites. Or if you have a database of websites, you could make a “Random Site” link – a fun thing to use with blogs.

The Code

<?
$global_dbh = mysql_connect("localhost","username","password");
mysql_select_db("mydatabasename", $global_dbh);

$query = "SELECT * FROM `urls` ORDER BY `lasttime` ASC LIMIT 1";
$result = mysql_query($query, $global_dbh);
$row = mysql_fetch_array($result);

$query = "UPDATE `urls` SET `lasttime`='".time()."' WHERE `ID`='{$row["ID"]}'";
$result = mysql_query($query, $global_dbh);

Header("Location: {$row["URL"]}\n\n");
exit();
?>

Database Requirements
In this example, you only need a table having two basic fields – ID, URL, and lasttime. The ID will make it easy to update the time, make sure that it is an auto-incrementing integer. lasttime is what we will use to make this a rotator, and not a random site. You simply pick the URL that has the smallest last time.

The Explaination
The first 3 lines should be easy to understand by now, if not you’ll want to read a basic PHP/MySQL tutorial.

Lines 5-7 select a url, but pick the URL with the smallest last time, which means it is the URL that hasn’t been viewed in the longest.

Lines 9-10 update the database with the current time for the URL choses. We use the ID, and not the URL, in case there are multiple entries for the same URL.

Line 12 is a simple redirection. Remember to keep the {}’s as those allow you to use the array inside the quotes.

Lines 13-14 simply end the script execution. This really isn’t needed with a standalone script, but remember that redirecting the user doesn’t stop execution of the script – and it could become an easy way to bypass a login script if you forget, so its always good to be in the habit of using exit() after a redirect, even when its a simple script.