Having worked with search engines for more than 5 years, I can tell you there's no standard way to retrieve the query value.
As other answers already told you, the first step is to inspect the
HTTP_REFERER header. Assuming you are using Rails, you can get it from the request
Otherwise, you need to extract it from request headers in an other way.
Once you have the referrer, then you are in front of 3 main possibilities:
- variable is empty. sorry, you can't do nothing
- variable is not empty, it's a search engine
- variable is not empty, it's not a search engine
The first option is simple. What you want to know is if the referrer is a search engine. If so, then you need to extract the query.
The most common way to do this is using a checklist. The checklist is usually a list of key/value where the key is the search engine domain and the value the name of the query string parameter that holds the query value.
This is the same approach used by Google Analytics. From the ga.js file
First host matches both key and value, first wins.