Published on: 2007-06-03 - Views: 3926

Digg! del.icio.us Furl reddit spurl bloglines ma.gnolia.com Yahoo MyWeb technorati blogmarks blinklist pixelgroovy Share this tutorial on tutorialicio.us! simpy
Here's a tutorial that explains how you can keep track of what kind of traffic search engines are sending to your site. We'll use a database table to store all the keywords that have been used to reach your site and we'll couple each keyword with the referring search engine. Go in phpMyAdmin, create a database and paste this code in the SQL window, this will create the table. In this table we'll store even the timestamp of the visit.
CREATE TABLE `keywords` (
`id` int(11) unsigned NOT NULL auto_increment,
`searchengine` varchar(10) collate latin1_general_ci NOT NULL,
`keyword` text collate latin1_general_ci NOT NULL,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
FULLTEXT KEY `keyword` (`keyword`)
) ENGINE=MyISAM
Now let's see some really simple php code: what we do is basically parse the referer url, find the search engine with a regular expression function (php eregi function)and store the search term in the database:
<?php
$ref = $_SERVER['HTTP_REFERER'];
$se = "";
if(eregi("msn",$ref))
{
$se = "msn";
$s=explode("?",$ref);
parse_str($s[1]);
$keyword = $q;
}
if(eregi("google",$ref))
{
$se = "google";
$s=explode("?",$ref);
parse_str($s[1]);
$keyword = $q;
}
if(eregi("yahoo",$ref))
{
$se = "yahoo";
$s=explode("?",$ref);
parse_str($s[1]);
$keyword = $p;
}
if(eregi("altavista",$ref))
{
$s=explode("?",$ref);
parse_str($s[1]);
$se = "altavista";
$keyword = $q;
}
if(eregi("ask",$ref))
{
$se = "ask";
$s=explode("?",$ref);
parse_str($s[1]);
$keyword = $q;
}
$connect = mysql_connect(host,user,password);
mysql_select_db(databasename , $connect);
$insert = mysql_query("INSERT INTO keywords VALUES (NULL,'$se','$keyword',NULL)");
mysql_close($connect);
?>
As you can see adding other search engines is easy, you just have to copy and paste one of the if blocks, replace the string with the search engine name and change thekeyword variable name depending on the variable used by the search engine you're adding. To see what variable it uses just run a search on the search engine and see the variable name that preceed the keyword, e.g http://www.google.com/search?q=php+tutorials as you can see the variable that contains the keyword is "q".