PHP Script – Show Google Search Term That Brought Visitor to Your Website

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

Continue reading “PHP Script – Show Google Search Term That Brought Visitor to Your Website”

Programming: IE8 and PHP $ SERVER[‘HTTP REFERER’]

IE Does Not Behave Like Firefox for Many PHP Variables
Forget it, IE doesn’t pass on the PHP referer variable.  You cannot rely on IE for the referer variable.

What’s really frustrating for LAMP programmers is that we often test in Firefox and things look great, and then you jump over to a Windows machine for QA and find out that IE doesn’t behave the same way.

Recently, I had to open a new window with a link from a page on website I was developing.  In order to validate that the new page opened had come from the same domain, I thought to use the referer code that PHP so conveniently keeps as a global session variable  ($ SERVER[‘HTTP REFERER’]).

However, this variable actually is reading from the Apache log of info that was sent in the header from the visitor.  Alas, not all browsers are alike, and hence you cannot rely on this variable to be populated.

Workaround:

It’s messy, but you can always rely on the PHP $_SESSION[‘id’] variable, since that is a server-side variable. It should always perform the same way regardless of the OS or browser that is using the site.

A simple way to check that the page opened has come from the page you sent it would look like this:

Origin page:

1. Populate the session variable:

session_start();
$_SESSION[‘id’] = session_id( );

Link by tagging on the session variable:

LINK to 2nd PAGE ?x= ECHO SESSION ID HERE

2. Next page

session_start(); //make sure to check that session is started
if (isset($_GET[‘x’])){$x=$_GET[‘x’];} //populate the get variable
if($x!=$_SESSION[‘id’]){
//test if the session variable sent from the first page, matches session here
//this area matches, do your things here
}else{
//no match, tell them to try again, etc…
}