PHP URL Redirect with MySQL logging

ShoeMoney did a video post about monetizing blogs. He’s rather critical of AdSense (has a fair few points too) but he did offer one piece of advice which I had been meaning to put in place for a while, and that is to use a redirection script to send people off to affiliate links as opposed to direct-linking them. So I went away and built a custom one for GO Blog.com.au, and thought I would share the code with everyone.

Save the following code as something like /url_redirect.php

<?php
if(!isset($_REQUEST[’to’]))
 $toURL = “http://www.goblog.com.au“;
else
 $toURL = $_REQUEST[’to’];

$time = time() ;

if (!get_magic_quotes_gpc()) {
$toURL = addslashes($toURL );
}

$db = mysql_connect(”localhost”, “goblog_urlredirect”, “dvs-dv8″);
if (! $db)
 die(”Couldn’t connect to MySQL”);
mysql_select_db(”goblog_urlredirect”) or die(”Could not access database: “.mysql_error());
mysql_query (”INSERT INTO toURL (url, time) VALUES (’$toURL’, ‘$time’)”);
mysql_close($db);
header (”Location: $toURL”);
?>

What does it do? It obviously provides a little more than just a nice redirect. It also allows me to monitor the number of users who follow those links (and with the date stamp it will let me sort over time). You will need a MySQL database set up with the something similar to the following table:

CREATE TABLE `toURL` (
`id` int(11) NOT NULL auto_increment,
`url` longtext NOT NULL,
`time` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Now any links to /url_redirect.php?to=http://google.com.au will be stored in your database and the user will be directed to the appropriate external link like normal.  

If something is confusing for you, let me know and I’ll try and explain. Enjoy!