ASP: Reading and Writing Cookies
Cookies are powerful things. Not only are they sweet and tasty, but they store useful information on your visitors’ computers as well! You can use them to check if a user has visited your site before, or store their login information, preferences, favorites, and other stats.
But how do you use them in ASP? This tutorial shows you just that.
The Commands
To write a cookie to the user’s computer, we use the Response.Cookies command.
Response.Cookies("CookieName") = SomeValue
To retrieve a cookie’s value, we simply call the command.
Dim CookieValue = Response.Cookies("CookieName")
ASP has probably one of the easiest implementations of cookies of any programming language. There are other attributes of a cookie we can set as well.
Let’s say our user has logged in.
<%
Dim strUserName = "Bob123"
Response.Cookies("UserName") = strUserName
Response.Cookies("IsLoggedIn") = True
Response.Cookies("UserName").Expires = Now() + 60
Response.Cookies("IsLoggedIn").Expires = Now() + 60
%>
We just gave the “UserName” and “IsLoggedIn” cookies an expiration date 60 days in the future (Now() + 60).
What if we want to check if our user is logged in, and display a welcome message accordingly?
<%
If Response.Cookies("IsLoggedIn") = True Then
Response.Write("Welcome, " & Response.Cookies("UserName"))
Else
Response.Write("Welcome, stranger!")
End If
%>
It’s as simple as that. But wait, there’s more! You can also make a cookie expire as soon as the user closes his or her browser; don’t set the Expires attribute at all.
To assign a specific date value for the expiration date:
<% Response.Cookies("UserName").Expires = #April 15, 2010# %>
Cookie Arrays
A cookie can contain a collection of multiple values. This is useful for, say, shopping carts where each item in your cart has several values assigned to it: product ID, quantity, base price, etc.
<%
Response.Cookies("Item")("ItemID") = 1234
Response.Cookies("Item")("BasePrice") = 74.95
Response.Cookies("Item")("Name") = "Deluxe 4-Slice Toaster"
%>
Finally, what if you want to get rid of a cookie? Since cookies can’t be removed, per se, you can set them to expire now and they will essentially cease to exist.
<% Response.Cookies("UserName").Expires = Now() %>
As you can see, there are many uses for cookies, and in ASP it is really quite simple to utilize them. I never made any use of cookies for a long time; I stuck to session variables for everything. Once I actually got into cookies, I could never go back. They’re an invaluable resource.
No comments yet.