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 :
We first check to see if our visitor has been referred to our site by google by checking the predefined variable $_SERVER[“HTTP_REFERRER”] for occurrences of the string http://www.google or http://google using the strpos() function. Then we parse the referrer 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 address, the keyword and date and time to the file.