Check what people searched in search engines for your site

Posted by Pete | Posted in PHP Tutorials | Posted on 12-11-2009-05-2008

0

Find out what people have searched on search engines to access your website. A similar feature can be found on google.com/webmasters but that’s is a 3′rd party script where as this can be hosted directly on your site.

So first we need to choose what search engines we want recorded. To do this I will do the examples on google and yahoo. First go to google.com and search for PK-Tuts then look into the address bar it will look something like this.
http://www.google.co.uk/search?hl=en&source=hp&q=PK-Tuts&btnG=Google+Search&meta=&aq=f&oq=
As you can see &q=PK-Tuts is what you searched for so what we need is the letter before the = and after the & which in this case is q. So now you have the query letter we need to put it in a format.

<?php
$search_engines = array("address_in_bar_without_ext" => "query_letter");
?>

Example

<?php
$search_engines = array("google" => "q", "yahoo" => "p");

Now we will detect any referrals from Google or Yahoo and what they searched. So lets get the referral url.

$url = parse_url($_SERVER["HTTP_REFERER"]); // Parse the referring url and assign it to $url
$host = trim(str_ireplace("www.", "", $url['host'])); // Get the hostname from the referring site and remove www. from it and any whitespace then assign it to $host.
parse_str($url['query'], $query); // Now parse the queries such as <strong>?hl=en&source=hp&q=PK-Tuts</strong> and allow us to grab the individual query then put them all in an array in $query.

Now we will go through the $search_engines array assigning the key(“google”) as $engine and value(“yahoo”) as $query.

foreach($search_engines as $engine => $query){ // Go through the array
	$engine_chk = stripos($host, $engine); // Check if the referring hostname has $engine in it anywhere.
	if ($engine_chk !== false) { // If it does then
	    echo "You have been referred by " . $engine . " to this site by searching for '" . $query . "'"; // Echo the message including the name of the search engine and what they searched for
	    /**
	     * DO YOUR DATABASE STUFF HERE
	     */
	}
}

With this you would be able to log the visits into a database so you could keep track of your best search engine and what they searched for.

So thats it thanks and if you have any comments or feedback please leave a comment.

Write a comment

You must be logged in to post a comment.

Tutorials Written By Peter Kelly