Cookie Examples Using ASP

There are many sites on the web that will ask you to register in order to get some level of enhanced access. Once you have registered, you are given a username and password. the next time you visit the site, you are asked to enter these before being granted access. Some sites will give the option of saving your username and password as a cookie, so that you will automatically be logged in the next time you visit. The example below will, hopefully, illustrate this.

1st Example:
The page will display the login screen for the user. They are asked to enter their email address and password. They can also click on a checkbox that will have their login information saved as a cookie.

2nd Example:
The login page will check for the existence of a cookie. The login check page will inform the user if their login was entered via a cookie, or by direct input.

Creating Cookies with ASP

The syntax for writing cookies:

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

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

OR

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

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.

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:

Reponse.Cookies("thesameCookieName")("somekey") = "SomeValue"
Reponse.Cookies("thesameCookieName")("anotherkey") = "AnotherValue"

The way the actual cookie will look like:
.sislands.com TRUE / FALSE 982399541
thesameCookieName somekey=SomeValue&anotherkey=AnotherValue

Notice the value of the cookie is really the URLencoding of the NAME=VALUE&NAME=VALUE pairs

ASP use 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 named theCookie has keys, then this value will be true. If not, then it will be false.