April 25, 2012

FInding out referring page (php)

Question by pg.

At my work I often need to figure out where our traffic comes from. We buy google ads and that traffic gets identified by a query string in the url. (mywebsite.com/?x=”google_ad_group_4″).

On every page I include some sessions stuff that sets $_SESSION[‘x’] to $_GET[‘x’] if $_GET[‘x’] is there. If there is no $_GET[‘x’] I go through some other options to see where they came from and set that in $_SESSION[‘x’]:

$refurl = parse_url($_SERVER['HTTP_REFERER']);
$query = $refurl['query'];
parse_str($query, $result);

if (isset($result['q'])&& strstr($_SERVER['HTTP_REFERER'],'google')) {
    $_SESSION['x'] = 'G-'.str_replace('\"',"X",$result['q']);
}elseif (isset($result['p'])&& strstr($_SERVER['HTTP_REFERER'],'yahoo')) {
    $_SESSION['x'] = 'Y-'.$result['p'];

//took out bing, aol, ask etc in the name of brevity

}else{
    if ($refurl['host']){
        $_SESSION['x'] = $_SESSION['x'].'_ref-'.$refurl['host'];
    }
}

This way I can append the search query that brought the user to the site and what search engine they used. I log the incoming $_SESSION[‘x’]’s.

Many users are coming in with $_SESSION[‘x’]’s of “_ref-mywebsite.com” which doesn’t make sense, if they were coming from my own domain, they’d have already had a $_SESSION[‘x’] set on whatever page they’d been on. Is this because they have their browser’s security turned up high or something?

Am I missing something obvious? Is there a smarter way to do this?

Answer by Starx

You can get the referrer like this

echo $_SERVER['HTTP_REFERER'];

But as mentioned in comment, it can easily be manipulated.

...

Please fill the form - I will response as fast as I can!