What is a cookie? A cookie is a small piece of information sent to a user’s browser by a web server. If a web site is programmed in a certain manner, its server will send information to your browser, which is stored on your hard drive as a text file. If you visit the same site later, the server can retrieve the cookie from your computer. Cookies are used to track web site visitors and retain user preferences. It’s fairly easy to use cookies in ASP and now I’ll show you how can you do that. Consider the following code:
<%
Response.Cookies("SweetCookie") = "true"
Response.Cookies("SweetCookie").Expires="December 31, 2004"
%>
If you add the code above, at the top of one of your ASP pages, whenever somebody visits this page, a cookie called SweetCookie will be written on his computer. The cookie is set to expire at the end of 2004. If you want your cookie to expire when your visitor closes his browser, all you need to do is NOT to set the Expires property of Response.Cookies.
Reading cookies in ASP is as easier as writing them, as you can see in the example below:
<%
sCookie = Request.Cookies("SweetCookie")
%>
You can use cookies to determine if a visitor has been on your website before (returning visitor), and display customized greeting message depending on that:
<%
If Request.Cookies("SweetCookie") = "true" Then
sResponse = "Welcome returning visitor!"
Else
sResponse = "Welcome new visitor!"
Response.Cookies("SweetCookie") = "true"
Response.Cookies("SweetCookie").Expires="December 31, 2004"
End If
Response.Write sResponse
%>
If the cookie called SweetCookie exists and it has value "true" then we set the value of the sResponse string variable to "Welcome returning visitor!". If the cookie doesn’t exist or it has value different than "true", then we set sResponse to "Welcome new visitor" and we write the cookie to the visitors machine, so we can greet him as returning visitor next time he drops by.
|