Thursday, September 28, 2006

Setting and Using Cookies in ASP

Cookies are used to store information specific to a visitor to your website. A cookie is stored on the visitor's computer. You can set the expiration date of a cookie. If you set that date for sometime in teh future, the cookie will remain on teh visitor's comuter until that date, or until the visitor manually deletes it. If you don't set an expiration date, a cookie last for the duration of the session.

Know that not everyone surfs with cookies on. Estimates are that about 6-10% of people surf with cookies off. If you relay on cookies, you're web site won't work right for these people. Cookies are a very common technology though and almost every site uses them. Still, you might want to check to see if your visitor has cookies enabled before you use them (which is a more complicated process than you might think).

Creating an ASP cookie:
Response.Cookies("FirstName") = "John"
This example creates a cookie named FirstName that stores the value 'John'.

Now that you've stored it, how do you read it? Easy:
Request.Cookies("FirstName")
If you want, you can assign the value of the cookie to a variable so you can use it without having to call the request object each time
Dim FName
FName = ""
FName = Request.Cookies("FirstName")
Response.write(FName)
If you want the cookie to last longer than the session, you can set an expiration date. Here's a cookie that lasts 10 days:

Response.Cookies("FirstName") = "John"
Response.Cookies("FirstName").Expires = Date() + 10
You can also set a cookie to last until a specific date:
Response.Cookies("FirstName") = "John" 
Response.Cookies("FirstName").Expires = #December 31,2009#
With the previous examples, I've only stored one value to the cookie. But cookies can hold more than one. You can make a cookie array or collection
Response.Cookies("Name")("FirstName") = "John"
Response.Cookies("Name")("MiddleName") = "Samuel"
Response.Cookies("Name")("LastName") = "Smith"
Response.Cookies("Name").Expires = Date() + 365
You address an array or collection item just like you do a single cookie
Response.write(Request.Cookies("Name")("FirstName"))
would show "John" on the screen.

Now go bake some cookies!

No comments: