Here is a simple php script that will detect if your visitor is coming from Google and then log the keyword used to reach your site to a file. The script logs the visitors ip address along with the keyword and exact date and time to a file in the form x.x.x.x googled for “key word here” on Month Date, Year, at Hours:minutes am/pm. To use the script, just paste the following code into your php pages , and set the variable $log_file appropriately.
Here is the code :
/* JUST A FEW SETTINGS FIRST
The log file name,
this is where the key words will be stored,
make sure to keep a difficult-to-guess name
for privacy reasons
*/
$log_file="google-keywords-log.log";
/*
Set your timezone (just to make sure you can analyze the data better)
Some useful time zone values :
Asia/Karachi
Asia/Dacca
Asia/Qatar
Asia/Muscat
Asia/Tokyo
for a complete list, refer to http://www.php.net/manual/en/timezones.php
*/
date_default_timezone_set("Asia/Calcutta");
// THE CODE
if (strpos($_SERVER[‘HTTP_REFERER’],‘http://google’) OR strpos($_SERVER[‘HTTP_REFERER’],‘http://www.google’)) {
$referer=$_SERVER[‘HTTP_REFERER’];
$url=parse_url($referer);
parse_str($url["query"],$query);
$data=$_SERVER[‘REMOTE_ADDR’]." googled for \"".$query["q"]."\" on ".date("F j, Y,")." at ".date("g:i a")."\r\n\r\n";
$fp=fopen($log_file,"a+");
fwrite($fp,$data);
fclose($fp);
}
?>
Code Explained
We first check to see if our visitor has been refered to our site by google by checking the predefined variable $_SERVER["HTTP_REFERER"] for occurences of the string http://www.google or http://google using the strpos() function. Then we parse the referer url using parse_url() function. Then we go on to parse the “query” component of the array returned by parse_url() using the parse_str() function which parses the strings as if it were the query string passed via a URL and sets variables in the current scope. Once the string is parsed into the array $query , we can access our keyword term at $query["q"] .Finally we open our log file (set in $log_file ) in the append mode (a+) and append the visitors IP adress, the keyword and date and time to the file.
