Check the Referrer of a Visitor

Dynamically check to see if a referrer is coming from a site in your network, by using this simple script.

<?php
// call this function without the http:// or any subdomains
function fromMyDomain($site){
global $_SERVER;
$referrer = $_SERVER['HTTP_REFERER'];

$siteRegEx = '/(http(s)?|ftp):\/\/([a-zA-Z1-9]+.)?'.$site.'\/(.)*/';
// creates a regex that will match http://$site, https://$site, ftp://$site
// as well as http://subdomain.$site

return preg_match($siteRegEx,$referrer);
}

?>
Thus we can tell: You came from elsewhere!
To use this code, simply put the function in a .php file and call:
<?php
if fromMyDomain(<MY_DOMAIN_NAME>){
// code to handle this case here! (ie echo 'You Came From BlueCentauri.com!';)
} else {
// code to handle this case here! (ie echo 'You came from elsewhere!';)
}
?>

This can be useful for custom 404 error pages, that can tell whether a visitor is coming from another domain. Here at Blue Centauri Consulting we use this code fragement to log 404s generated by bad links on our site. Otherwise, our log file becomes full of search engine bots who haven't updated their links yet.

Perhaps you want to see what the domain name is of the referrer. In that case, you may want to try this snippet of code.

<?php
function getReferrerDomain(){
global $_SERVER;
$referrer = $_SERVER['HTTP_REFERER'];
// we can't always see the true referrer
if ($referrer == ''){
return 'Direct Link or Behind a Fire Wall';
}

// get the domain up to the slash
$endIdx = strpos($referrer, '/', 8 );
return substr($referrer,0,$endIdx);

}
?>

In this case, we can see you came from Direct Link or Behind a Fire Wall

A Word of Caution

We've found most visitors don't like to know you can identify where they've clicked from. That is why we tend to use the second function, getReferrerDomain, for internal purposes only.

Copyright © 1996 - 2012 by Sarah K Tyler
Part of the SKTyler.com Network