Find the Google Search Term Keywords That Landed the Visitor on Your Website

I always wanted to know when displaying the webpage what search brought the user to this page.  You can always look at Google Analytics, or whatever statistics package you have on your server (Urchin, Webalizer, etc…), but that is after the fact.  So, I wrote a simple PHP script (all server-side) that gives you that information.

Code Example: Full script – Copy & Paste

referaltest.php

$referer= $_SERVER['HTTP_REFERER'];

//find the search query from google that brought them here
$qref= strpos($referer,’google’);

if($qref!=”){
$qstart = strpos($referer,’q=’);
$qend = strpos($referer,’&’,$qstart);
$qtext= substr($referer,$qstart+2,$qend-$qstart-2);
$qtext= str_replace(‘+’,’ ‘,$qtext);
}
echo $qtext

It’s that simple… See below for more explanation and additional samples.

Step By Step Explanation of Script

$referer= $_SERVER['HTTP_REFERER'];

Populate the PHP server variable that tells you the full path of the where the user came from.
Note: This field can be blank or incomplete depending on several factors on the user/searchbot’s server settings – but for the purposes of this script, we are just looking at this variable for specific information from Google.

$qref= strpos($referer,’google’);

Use PHP STRPOS() to find the needle in the haystack. In this case, we are looking for the term google in the referer field. Note, this PHP function is case sensitive, so make sure you stay with all small letters here. (And for other search engines, where the value is not lowercase, you must match that specifically as well).

$qstart = strpos($referer,’q=’);

Find the starting position of the “q=” term, which is where google tells you in this referer string what search term brought the visitor here.

$qend = strpos($referer,’&’,$qstart);

Find the ending of the search term – The & indicates the variable, so we’ll end it here.

$qtext= substr($referer,$qstart+2,$qend-$qstart-2);

strip the rest of the string, leaving us with the search term and with pluses in between.

$qtext= str_replace(‘+’,’ ‘,$qtext);

Remove the + characters that Google places between search terms

echo $qtext

Print out the Google Search that brought the visitor to this page. You can of course now put this variable into a session variable and use it throughout the session, or store it to a database for tracking searches in to your site, etc…

Likewise, you can use this technique for any search engine, such as Yahoo, Bing, etc… You just need to find the search term pattern and how it appears in the referer variable that the PHP Server variable returns.