I'm working on a script that will save the refering url for each visitor to a session var and then store it to the db with other data like the google keyword/phrase that brought the visitor to the website as well as if the refering link was a regular google listing (aka organic result) or a paid link (google adwords). So far I've come up with this but it doesnt always work. Doing more reading I've found that in several conditions http_referer is blocked or hidden so I'm looking for a better way to get this working.
$session = & JFactory::getSession();
if (!$session->get('referrer', $origref, 'extref')) //If does not exist
{
$origref = $_SERVER['HTTP_REFERER'];
$session->set('referrer', $origref, 'extref');
$url = $session->get('referrer', $origref, 'extref');
if(!$url && !$url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false) {
$q = 'No referer';
}
$parts_url = parse_url($url);
$query = isset($parts_url['query']) ? $parts_url['query'] : (isset($parts_url['fragment']) ? $parts_url['fragment'] : '');
if(!$query) {
$q = 'Not from Google';
}
parse_str($query, $parts_query);
$q = isset($parts_query['q']) ? $parts_query['q'] : isset($parts_query['oq']) ? $parts_query['oq'] : (isset($parts_query['p']) ? $parts_query['p'] : 'could not fetch keyword');
if(stristr($origref, 'aclk')) { // if referer is a google adwords link as opposed to an organic link
$type = ', paid link, '.$_SERVER['HTTP_USER_AGENT'];
} else {
$type = ', organic result, '.$_SERVER['HTTP_USER_AGENT'];
}
$ginfo = $q.$type;
$session->set('referrer', $ginfo, 'extref');
}
function search_engine_query_string($url = false) {
if(!$url && !$url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false) {
return 'No referer';
}
$parts_url = parse_url($url);
$query = isset($parts_url['query']) ? $parts_url['query'] : (isset($parts_url['fragment']) ? $parts_url['fragment'] : '');
if(!$query) {
return 'Not from Google';
}
parse_str($query, $parts_query);
return isset($parts_query['q']) ? $parts_query['q'] : (isset($parts_query['p']) ? $parts_query['p'] : '');
}
Any ideas?
Another typical method is to have a specialized entry url for a tracker identity. For example:
subdomain.mysite.com/tracker?userid=12345&source=adwords
When that url is hit, then you know the source is adwords, and you would immediately redirect the user back to the main page with a header
redirect. That way, they have no idea about the tracking, and it should be pretty reliable.
I might be wrong, but unless you control both ends (that is, the referrer and the referred) I don't think it's possible beyond what you're already doing.
If it's for analysis purposes, you can use Google Analytics and Google Webmaster Tools.
They both complement each other, and do pretty much want you want to accomplish with your script