Cookies with Keys

In Cookies we worked with simple cookies that only had one value associated with them. Cookies can also store multiple values of related information. When this is the case they are said to have Keys.
For example just say you wanted to create a cookie to keep track of 3 pieces of personal information about a visitor. Instead of creating 3 different cookies, you could create one cookie (PersonalDetails) with 3 keys as in example 1.

Example 1:

<%
Response.Cookies(“PersonalDetails”)(“FirstName”)=”Michael”
Response.Cookies(“PersonalDetails”)(“SurName”)=”Wall”
Response.Cookies(“PersonalDetails”)(“CountryofBirth”)=”Ireland”
%>

You can find the value of a cookie subkey by using the following syntax:

syntax: Request.Cookies(NameofCookie)(NameofSubKey)

So for our code in example 1 above we could use the code below to retrieve this cookie PersonalDetails with its 3 keys and write them out.

<%
Response.write Request.Cookies(“PersonalDetails”)(“FirstName”) & "<br>"
Response.write Request.Cookies(“PersonalDetails”)(“SurName”) & "<br>"
Response.write Request.Cookies(“PersonalDetails”)(“CountryofBirth”) & "<br>"
%>

The result would be:

Michael
Wall
Ireland

Remember that unless you set the Expires attribute, the cookie will only last as long as you have the browser open. You could set the Expires attribute as below in example 2.

Example 2:

<%
Response.Cookies(“PersonalDetails”)(“FirstName”)=”Michael”
Response.Cookies(“PersonalDetails”)(“SurName”)=”Wall”
Response.Cookies(“PersonalDetails”)(“CountryofBirth”)=”Ireland”
Response.Cookies(“PersonalDetails”).Expires=Now() + 60
%>

Using the HasKeys Property

We can use the HasKeys property to determine whether or not a cookie holds multiple values.

Syntax: Request.Cookies(“theCookieName”).HasKeys

Again if we wanted to determine whether our cookie PersonalDetails created in example 1 had keys we could run the code in example 3.

Example 3:

<%
BlnValue=Request.Cookies(“PersonalDetails”).HasKeys
%>

If the cookie named PersonalDetails has keys, then the variable BlnValue will be true otherwise the value will be false.

Returning all the cookies and their values

If you wanted to check what cookies your server has sent to the user's computer you could run the code below. It checks for what cookies have been written and if they have keys.

<html>
<body>
<%
Dim cookie, cookieKey
For each cookie in Request.Cookies
Response.write "<p>"
If Request.Cookies(cookie).HasKeys then
For each cookieKey in Request.Cookies(cookie)
Response.write cookie & ":" & cookieKey & "=" & _
Request.Cookies(cookie)(cookieKey)
Response.write "<br>"
Next
Else
Response.Write cookie & "=" & Request.Cookies(cookie) & "<br>"
End if
Response.write "</p>"
Next
%>
</body>
</html>

ASP/.NET Hosting

ASP.NET Web Hosting – 3 Months Free!

MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.