Using the referrer (http://www.netmechanic.com/news/vol4/javascript_no14.htm) you can find where the user comes from. Then it's just a matter of parsing it correctly.
I saw this script :
function getkeywords() {
var x = document.referrer;
var lastparturl = 0;
if (x.search(/google/) != -1) {
lastparturl = x.indexOf("&btnG=Google+Search");
x = x.slice(38,lastparturl);
x = x.concat("via google");
}
else if (x.search(/yahoo/) != -1) {
lastparturl = x.indexOf("&ei=UTF-8&iscqry=&fr=sfp");
x = x.slice(63,lastparturl);
x = x.concat("via yahoo");
}
else if (x.search(/ask.com/) != -1) {
lastparturl = x.indexOf("&search=search&qsrc=0&o=0&l=dir");
x = x.slice(25,lastparturl);
x = x.concat("via ask");
}
else if (x.search(/dogpile/) != -1) {
lastparturl = x.indexOf("/1/417/TopNavigation/Relevance/iq=true/zoom=off/_iceUrlFlag=7?_IceUrl=true");
x = x.slice(46,lastparturl);
x = x.concat("via dogpile");
}
else if (x.search(/altavista/) != -1) {
lastparturl = x.indexOf("&kgs=1&kls=0");
x = x.slice(48,lastparturl);
x = x.concat("via altavista");
}
else {
x = "no keywords available";
}
x = x.replace(/+/, " ");
return x;
}
Here http://www.webmonkey.com/codelibrary/Get_Referrer_Keywords
I'm not sure if it works perfectly, but it worked OK when I reached their website through google.
I also saw that some scripts that you can download do that, for instance : http://webscripts.softpedia.com/script/Search-Engines/Keyword-Grabber-45299.html
Again, this will need to be tested.