29th July 2008

How to get search engine (Google, Yahoo, MSN) referal keywords using PHP

There are many reasons why you'd want to know what keywords your current visitor entered your website on; whether you want to show them similar content, gather opinion or maybe show a targetted piece of advertising, the bigger question is "how?". I recently (through boredom more than necessity) gave this a go, so I'll show you how I did it.

What I wanted to achieve

On Seopher.com I receive quite a lot of traffic from Google - a good 60-70% of my traffic is natural search oriented. I wanted a way to offer a richer experience to these users and try to increase the number of pages they view. So the objective was to take the keywords they entered in on and provide a list of similar articles.

PHP Functions

First off let's look at the functions I've written to get the job done.

This first function (getReferalHost) simply obtains the referal URL and uses the PHP function parse_url() to break things down. Then it's a simple set of 'if' statements to return a user-friendly hostname. So whereas the hostname might be images.google.com, I'm using "strstr" to check whether the string 'google' is in the URL, and so on. It's not foolproof but it's okay.

This next function (getKeywords) parses the referal URL again (not best practice is it? Shame on me). Then I've got a specific preg_match for each of the different vendors (based on the URLs that each of them uses. Google will format their query as such: http://www.google.com/search?&rls=en&q=seopher+another+keyword so I know that what I'm after starts with '&q=' with the keywords separated by '+'. So the regex used matches that. Yahoo and MSN do exactly the same, just with slightly different syntax - hence the need for the 'if' statement.

Really you can add as many different vendors to this function, I'm just focusing on the obvious 3 because they constitute about 98%+ of my search traffic.

This final function is what I'm using to write the recommendations; it takes the keywords used as a parameter and uses MySQL scoring to deliver results... So it takes the search terms and tries to find similar content on the website:

Usage

Using these functions is really simple, I've commented my code so you can see the method behind the madness:

Done! This example is pretty specific to what I'm doing but it shows you how I'm getting keyword data back. The functions should be pretty re-usable too (bar the getSearchHelperList which is bespoke to my needs). I'm not providing a download with this one because there's not enough to download, but the demo has instructions on what to do.

Tagged with php