Extract Search Query from Google HTTP Referer

By Hawkee on Nov 19, 2008

This will extract the search query from a Google search. It doesn't specifically look for Google in the referer so it may capture more than just Google searches. You can use this information to re-perform the search on your own site or just keep it for your own records.

$referer = $_SERVER[HTTP_REFERER];

    preg_match("/[\&\?]q=([^&]*)/", $referer, $matches);

        $search_query = rawurldecode($matches[1]);
        $search_query = str_replace("+", " ", $search_query);

print "You searched Google for '$search_query'";


Sign in to comment.
vaseline28   -  Nov 20, 2008

Really like this :)
+ Like

F*U*R*B*Y*   -  Nov 19, 2008

Nice, Very Nice :)

Hawkee   -  Nov 19, 2008

You can just change the preg_match to work with any other engine. Just change the q to the name of the variable.

lostdeviant   -  Nov 19, 2008

Nice snippet. I'd love a version for search engines that don't use q=

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.