Using Cookies in ASP

A web site might have had a thousand visitors, but for all the web site coordinator could know, every visit might have been made by the same visitor! Cookies were introduced as a method of identifying and marking each different visitor to a web site.

 

Cookies are text files written by the client browser, containing information sent by a server, which reside on the user’s computer. They store information about the user, and are used by a particular server (or server within the same sub-domain) that the user has visited previously to personalize web pages, and determine where a user has been before within the same domain. They can then be used to keep users up to date with relevant information. Each web server, when a user accesses it, can send a cookie, which the user must accept if the server is to read the cookie on the user’s machine during future visits. If the user doesn’t accept the cookie, it can’t be read by the server in future.

 

There are all sorts of cookie myths on the Internet. Mostly they revolve around the notion that a smart programmer can get unauthorized information from a user, violating the user’s ” right to privacy”. Let’s set the record straight. A cookie can only store information, which the user sends voluntarily or selects on a page and that can only happen if the “accept cookies” option in the browser is turned on by the user. No one can get your e-mail address or your home address if you don’t voluntarily send the information by filling and submitting a form.

 

Individual cookies on Netscape are limited to 4kb of data. On IE5 the theoretical size is unlimited. The maximum number of cookies is also browser specific and once this limit is reached, the oldest cookie will be deleted to make room for the newest one. So make sure you use cookies judiciously.

The Cookies Collection

the Request object has a Cookies collection – it’s now time to talk about this collection. The Cookies collection holds information from all the cookies set by any one application. That is, when a client establishes a session with the server the values that the server reads from the client’s cache of cookies are held in the Cookies collection. This means that they are available for easy access by the server.

Unlike the Form and Querystring collections, the Cookies collection does not have a Count property but, like the Form collection, it can hold multiple values for the same cookie name. When this happens, the cookie is said to have keys, and each key holds a separate value.

 

Domains and servers can only read cookies that they themselves have set. If server X writes a cookie, then server Y cannot read it. If domain http://Myapp sets a cookie, then domain http://MyApp2 cannot read the cookies set by MyApp, and vice versa, unless the second domain is a sub domain of the first. When demanded by the server, the cookie that comes with the request is read-only. You can set the value for a cookie using the Response object, which you will learn about later in this chapter.

 

The general syntax for retrieving cookies is:

 

Request.Cookies(”cookie“)[(”key“)].attribute

 

So display the contents of a cookie in your web page you could use:

 

Response.Write Request.Cookies(”cookie“)

Creating Cookies with the Response Object

As well as reading information supplied by a client’s cookies, the server needs to be able to write information to cookies on the client’s machine. ASP uses the Response object’s features to set cookies’ values.

 

Until ASP was released, the most common way to set cookies was using CGI or in client-side JavaScript. The syntax for doing this with JavaScript is fairly complex – even daunting – if you’re not over-familiar with JavaScript. ASP (with VBScript) provides a one-line instruction method to set and retrieve cookies.

 

The syntax for writing cookies in ASP is:

 

<% Response.Cookies(”cookie”) = value %>

 

If value is a string, it must be enclosed in quotes.

 

If you use this method to set a cookie, the following HTTP header is generated:

 

Set-Cookie:YOURCOOKIENAME=somevalue

 

You can see that the Response.Cookies method is simply a way of sending the Set-Cookie HTTP header without resorting to complicated code. Therefore you should use Response.Cookies before you write any data in the response body.

Using Keys

If you add a key value, then you can access this cookie like a collection. This means that one cookie can have multiple values stored with it.

 

<% Response.Cookies(”cookie”)(”key”) = value %>

If a cookie is used to store more than one value we have to specify which of these multiple values we want to set. To do this, we refer to it via its key value. The key value is similar to a variable name. The general syntax for writing cookies with keys is:

Response.Cookies(”thesameCookieName”)(”somekey”) = “SomeValue”

Response.Cookies(”thesameCookieName”)(”anotherkey”) = “AnotherValue”

If you issue another cookie with the same name but without specifying the key, you will overwrite all cookie values for that cookie’s name.

The HasKeys Property

ASP uses the HasKeys property to determine whether or not a cookie holds multiple values. To check if a cookie holds multiple values, we interrogate the HasKeys property:

Request.Cookies(”theCookie”).HasKeys

If the cookie theCookie has keys, this statement returns True, otherwise it returns False. To iterate through the individual values for cookies with keys, use this model script:

For Each Cookie in Request.Cookies

If Request.Cookies(Cookie).HasKeys Then

For Each CookieKey in Request.Cookies(Cookie)

Response.Write(Cookie) & ” .”

Response.Write(CookieKey) & ” =”

Response.Write(Request.Cookies(Cookie)(CookieKey))

Next

Else

Response.Write(Cookie) & ” =”

Response.Write(Request.Cookies(Cookie)) & ” <BR>”

End If

Next

Making your Cookie Persist

A cookie set with the basic syntax will persist for as long as the browser is open, or until the session expires. As soon as the browser is closed, the cookie’s value will disappear.

To make a cookie persist, i.e., for the cookie to be written to the client browser’s hard disk (the “cookie jar”), you have to set an expiration date for the cookie. The general syntax for doing this is:

Response.Cookies(”Cook”).Expires = “July 4, 2001″

A Better Way to Set a Cookie’s Expiration Date

Though setting the cookie’s expiration date as ” July 4, 2001″ works, a better way to set the expiration date is to use relative date values. This is also better when the client and server are in different time zones. Since Date is a built-in VBScript function, you could set the expiration date as Date + X, where X stands for the number of days you want the cookie to “live”:

Response.Cookies(”Cook”).Expires = Date + 1

This will set the expiration date to 1 day from today.

Deleting a Cookie

To delete a cookie, set its Expires property to any date prior to today. The easiest way to do this is to use relative date values, as shown in this example:

 

Response.Cookies(”Cook”).Expires = Date - 1

 

Again, this technique could fail due to different time settings on server and client, so maybe something like Date – 1000 would be more secure.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • YahooMyWeb
  • Yigg

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)