Occasional you’ll want to control how people leave your site. Maybe it’s to let them know they will be going to a different site, maybe it’s just to control who gets linking credit for search engine spiders, or maybe you want the to see one more ad before leaving. In any case, here’s how I’ve solved the problem when asked by clients.

First some javascript to turn all links into redirects to a specific page…

<script>
function catchOutLinks()
  {
  for (i=0; i < document.links.length; i++)
    {
    var url = window.location.protocol + "//"
        + window.location.host;
    if((document.links[i].href.indexOf(url)>-1))
      {
      // ignore local links
      }
    else
      {
      oldref=document.links[i].href;
      document.links[i].href='/leaving.php?url='+oldref;
      }
    }
  }
</script>

Place that in the <head></head> portion of whatever template will be used to display pages you want outlinks on. To activate it you can either use an onLoad statement in your <body> tag, i.e….

<body onLoad="catchOutLinks()">

…or use this in the footer, below any other links…

<script>
catchOutLinks();
</script>

Next you’ll want to create a page using your regular template, but for the content use the following…

<?
$url=$_GET['url];
?>
You will be redirect to <?=$url; ?>
<META http-equiv="refresh" content="3;URL=<?=$url;?>>

Save the file, and make sure it’s a php file (has the extension .php) and in the javascript above, change “/leaving.php” to the url of the file you just saved.

One Response to “Capturing outlinks”

About me

I've been developing web sites for over 12 years. I started with HTML, moved on to Perl and now do mostly PHP with a lot of MySQL and Javascript as well.

The purpose of this blog is to write about many of the simpler scripting solutions bloggers are either unaware of or unable to implement. Hopefully I'll have something you can use

Danny Carlton

Advertising
Advertising

Switch to our mobile site