Home     Articles & Projects     Products & Web Services

Unversal redirection script

This is a simple way to store links in a database, and then redirect your visitors to those links via a jump script and a "link ID" instead of rendering the actual link into your page. This could be used, for example, where you have obtained product URLs from an Affiliate API, and instead of displaying the actual affiliate URLs in your page you want to use a local URL that will redirect to the actual affiliate URL.

This project requires a single table called "links", containing the following fields:

id (INT, Auto-Increment, Primary Key)
hash (VARCHAR(32), Unique)
url (TEXT)

You can either create this table manually using a tool such as phpMyAdmin, or use the following script to create the table for you. This script only needs to be run once:

create.php

<?php
 
// don't forget to set your own database connection settings!!
 
$connection = mysql_connect("localhost","username","password");
  if (!
$connection) {print mysql_error();exit();}
 
mysql_select_db("database", $connection);
 
$sql = "
CREATE TABLE `links` (
  `id` int(11) NOT NULL auto_increment,
  `hash` varchar(32) NOT NULL,
  `url` text NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `uid` (`hash`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  "
;
 
$result = mysql_query($sql,$connection);
  if (!
$result) print mysql_error($connection);
  print
"Done.";
?>

We are going to implement this as a PHP library file, which will be included by the redirection script (jump.php) and your main script. Here's the code:

jumplib.php

<?php
 
// As this is a library file for you to include in any project, notice how I
  // have prefixed every variable and function name with the library name.....
  // **************************************************************************
  // don't forget to set your own database username password and database name
 
$jumplib_connection = mysql_connect("localhost","username","password");
  if (!
$jumplib_connection) { print mysql_error();exit(); }
 
mysql_select_db("database", $jumplib_connection);
 
// **************************************************************************
  // FUNCTION: jumplib_getID($url)
  // Get a jump ID for $url.  First check to see if the URL already exists in the
  // database, and if so return the ID.  Otherwise, insert and return the new ID
  // We index and search by a hash value as this is far more efficient than
  // having an index on the actual URL field!
  // **************************************************************************
 
function jumplib_getID($url)
  {
    global
$jumplib_connection;
   
$hash = md5($url);
   
$sql = "SELECT id FROM links WHERE hash='".$hash."'";
   
$result = mysql_query($sql,$jumplib_connection);
    if (
mysql_numrows($result))
    {
     
$link = mysql_fetch_assoc($result);
      return
$link["id"];
    }
    else
    {
     
$sql = "INSERT INTO links SET hash='".$hash."',url='".mysql_escape_string($url)."'";
     
mysql_query($sql,$jumplib_connection);
      return
mysql_insert_id($jumplib_connection);
    }
  }
 
// **************************************************************************
  // FUNCTION: jumplib_getURL($id)
  // Get the URL for an ID
  // **************************************************************************
 
function jumplib_getURL($id)
  {
    global
$jumplib_connection;
   
$sql = "SELECT url FROM links WHERE id='".mysql_escape_string($id)."'";
   
$result = mysql_query($sql,$jumplib_connection);
   
$link = mysql_fetch_assoc($result);
    return
$link["url"];
  }
?>

Finally, the jump script itself:

jump.php

<?php
 
require("jumplib.php");
 
$url = jumplib_getURL($_GET["id"]);
 
// redirect using HTTP status code 302 (Moved)
 
header("Location: ".$url);
  exit();
?>

To use this in your own application, simply require("jumplib.php") at the top, and then call jumplib_getID($url) wherever you want to get an ID for a URL, and then render the link as:

"jump.php?id=".jumplib_getID("http://www.example.com/")

Here's an example script to test the library and show it in action:

test.php

<?php
 
require("jumplib.php");
 
  print
"<p><a href='jump.php?id=".jumplib_getID("http://www.example.com/")."'>example.com</a></p>";

  print
"<p><a href='jump.php?id=".jumplib_getID("http://www.example.org/")."'>example.org</a></p>";
?>

Click here to see this running on this server...

If you run the script, and hover your mouse over the links, you should see jump.php in the address bar instead of the actual URL...

Comments

Hi David, I have tested it

Hi David,

I have tested it and it works fine thanks. However there is something I don't understand how the links are still pointing to shopping.com instead of the affiliates ?
I have put the results here http://citishoppingguide.co.uk/shop/search.php?q=laptop

Thanks,

Robert

Hi Robert, That's entirely

Hi Robert,

That's entirely down to what URLs are contained in the response to your request to the shopping.com API. Is there anything in the shopping.com API documentation that discusses what sort of links are returned?

Hi David I have tried to

Hi David I have tried to implement this script and all works fine until you click on the link and instead of taking you to the link it takes you to a blank page see here:
www.smartgardening.co.uk/garden_power_tools_machinery/lawnmowers.php

In the right menu, there are two links for Mower Warehouse. The top one is a normal link in the page and the second is the redirect.
Do you know what might be affecting it?

Many Thanks
Kelly

Hi Kelly, I can see what's

Hi Kelly,

I can see what's happened - the link in the jump database has been URL encoded; which means that when it is returned to the browser as a URL none of the usual parameters appear correctly, because instead of & it is using &amp;...

I've checked the script above, and I can't see any point at which the URL would be url encoded within jumplib, so could you perhaps post the section of code where you are generating the link and I'll see if I can see where the encoding is taking place....

Cheers,
David.

Original link <p> <a

Original link

<p> <a href="http://track.webgains.com/click.html?wgcampaignid=35359&amp;wgprogramid=896&amp;wgtarget=http://www.mowerwarehouse.co.uk/acatalog/LAWN_MOWERS.html" target="_blank" rel="nofollow"><strong>Lawnmowers at Mower Warehouse &gt;&gt;&gt; </strong></a></p>

Jump Link

<?php
 
print "<p><a href='../jump.php?id=".jumplib_getID("http://track.webgains.com/click.html?wgcampaignid=35359&amp;wgprogramid=896&amp;wgtarget=http://www.mowerwarehouse.co.uk/acatalog/LAWN_MOWERS.html")."' target='_blank'><strong>Lawnmowers at Mower Warehouse &gt;&gt;&gt;</strong></a></p>";
?>

Cheers David

Hi Kelly, I see what's

Hi Kelly,

I see what's happening. As the original links are already HTML entity encoded, it will be necessary to "decode" them within the jump script (being the most convenient place to do it!). This shouldn't affect other networks who's URLs are not encoded. The reason the original links work fine is because the browser is decoding the entities.

To fix this, try changing your jump.php to the version below:

<?php
 
require("jumplib.php");
 
$url = jumplib_getURL($_GET["id"]);
 
// redirect using HTTP status code 302 (Moved)
 
$url = html_entity_decode($url);
 
header("Location: ".$url);
  exit();
?>

Cheers,
David.

Many thanks - worked a

Many thanks - worked a treat!
Kelly

Hi David I am working on a

Hi David

I am working on a site where the links and link text are dynamic. I want to place the redirect script, but I can seem to get it right

This is the current link:

Visit <a href="<?php echo $row_rstGetMerch['merch_url']; ?>" target="_blank"><?php echo $row_rstGetMerch['name']; ?></a>

How would I adapt
<?php print "<p><a href='jump.php?id=".jumplib_getID("http://www.example.com/")."'>example.com</a></p>";?>

to include the variables?

kelly

Hi Kelly, Use; <?php print

Hi Kelly,

Use;

<?php print "<p><a href='jump.php?id=".jumplib_getID($row_rstGetMerch['merch_url'])."'>$row_rstGetMerch['name']</a></p>";?>

...in this instance!

Cheers,
David.