views:

156

answers:

4

When I search for something such as "rearrange table columns in asp.net" on Google, and click the link to Wrox's forum site, the site greets me with a message such as "Your Google search for 'rearrange table columns in asp.net' brought you to Wrox Forum...".

How does a site know what query I typed into Google? And how could I add such an ablity to my site?

+6  A: 

It uses a header known as the "HTTP referrer". See http://en.wikipedia.org/wiki/HTTP%5Freferrer

To use it in your site, you would need some kind of dynamic page generation, such as ASP / ASP.NET, PHP, or Perl. For example in Perl, you could do something like:

if ($ENV{HTTP_REFERER} =~ /google.com\?.+&q=(.+?)&/)
    print "Your google search of $1 brought you to this site";

WARNING: The code above is only an example and may not be correct or secure!

JoelFan
+11  A: 

It is parsing your query from the query parameters in the HTTP_REFERER server variable, which contains the URL you're coming from and is provided in your HTTP request.

recursive
+1 for proper spelling. 3 R's, not 4!
Jim Lewis
+1  A: 

It looks at the referrer header. Here is some fairly basic PHP code to do it.

robertc
+1  A: 

Like these guys are suggesting, it's the HTTP_REFERER header variable. The query is in the "q" key in the URL. So if you want to parse that, you can just sort out the querystring and URL decode the "q" variable.

Jason