Chapter 9
Cookies
A cookie is a token that either a client browser sends to a Web server, or that
a
Web server sends to a client browser. Cookies allow a set of information to be
associated with a user. ASP scripts can both get and set the values of cookies
by using the Cookies collection.
9.1- Using the Cookies Collection with the Response
Object:
The Cookies collection sets the value of a cookie. If the specified cookie does
not exist, it is created. If it exists, it takes the new value and the old value
is
discarded.
Response.Cookies(cookie)[(key)|.attribute] = value
The parameter cookie is the name of the cookie. The parameter key is an optional
parameter. If key is specified, cookie is a dictionary, and key is set
to value. The parameter attribute specifies information about the cookie itself.
The attribute parameter can be one of the following.
Expires Write-only. The date on which the cookie expires.
Domain Write-only. If specified, the cookie is sent only to
requests to
this domain.
Path Write-only. If specified, the cookie is sent only
to requests to
this path. If this attribute is not set, the application path
is used.
Secure Write-only. Specifies whether the cookie is secure.
HasKeys Read-only. Specifies whether the cookie contains keys.
The parameter value specifies the value to assign to key or attribute.
If a cookie with a key is created, for example:
<%
Response.Cookies("mycookie")("type1") = "sugar"
Response.Cookies("mycookie")("type2") = "ginger snap"
%>
The following header is sent:
Set-Cookie:MYCOOKIE=TYPE1=sugar&TYPE2=ginger+snap
A subsequent assignment to myCookie without specifying a key, would destroy
type1 and type2. This is shown in the following example.
<% Response.Cookies("myCookie") = "chocolate chip" %>
The preceding example, the keys type1 and type2 are destroyed and their
values are discarded. The myCookie cookie now has the value "chocolate chip".
Conversely, calling a cookie with a key destroys any nonkey values it might
have contained. For example, if after the preceding code, you call
Response.Cookies with the following:
<% Response.Cookies("myCookie")("newType") = "peanut butter" %>
The value chocolate chip is discarded and newType would be set to peanut butter.
To determine whether a cookie has keys, use the following syntax:
<%= Response.Cookies("myCookie").HasKeys %>
If myCookie is a cookie dictionary, the preceding value evaluates to TRUE.
Otherwise, it evaluates to FALSE.
You can use an iterator to set cookie attributes. For example, to set all of the
cookies to expire on a particular date, use the following syntax:
<%
For Each cookie in Response.Cookies
Response.Cookie(cookie).ExpiresAbsolute = #July 4, 1997#
Next
%>
You can also use an iterator to set the values of all the cookies in a
collection,
or all the keys in a cookie. However, the iterator, when invoked on a cookie
that
does not have keys, does not execute. To avoid this you can first use the
.HasKeys syntax to check to see whether a cookie has any keys. This is
demonstrated in the following example:
<%
If Not cookie.HasKeys Then
'Set the value of the cookie
Response.Cookies(cookie) = ""
Else
'Set the value for each key in the the cookie collection
For Each key in Response.Cookies(cookie)
Response.Cookies(cookie)(key) = ""
Next key
%>
The following examples demonstrate how you can set a value for a cookie and
assign values to its attributes.
<%
Response.Cookies("Type") = "Chocolate Chip"
Response.Cookies("Type").Expires = "July 31, 1997"
Response.Cookies("Type").Domain = "msn.com"
Response.Cookies("Type").Path = "/www/home/"
Response.Cookies("Type").Secure = FALSE
%>
9.2- Using the Cookies Collection with the Request Object:
Here we will discusses how to gain access to cookies a browser sends to your
Web server. For information about accessing cookies your Web server sends to a
browser.
Request.Cookies(cookie)[(key)|.attribute]
The cookie parameter specifies the cookie whose value should be retrieved.
The key parameter is an optional parameter used to retrieve subkey values from
cookie dictionaries. While the attribute parameter specifies information about
the cookie itself. The attribute parameter can be one of the following.
HasKeys Read-only. Specifies whether the cookie contains keys.
You can access the subkeys of a cookie dictionary by including a value for key.
If a cookie dictionary is accessed without specifying key, all of the keys are
returned as a single query string. For example, if MyCookie has two keys, First
and Second, and you do not specify either of these keys in a call to
Request.Cookies, the following string is returned.
First=firstkeyvalue&Second=secondkeyvalue
If two cookies with the same name are sent by the client browser,
Request.Cookies returns the one with the deeper path structure. For example, if
two cookies had the same name but one had a path attribute of /www/ and the
other of /www/home/, the client browser would send both cookies to the
/www/home/ directory, but Request.Cookies would only return the second cookie.
To
determine whether a cookie is a cookie dictionary (whether the cookie has keys),
use the following script.
<%= Request.Cookies("myCookie").HasKeys %>
If myCookie is a cookie dictionary, the preceding value evaluates to TRUE.
Otherwise, it evaluates to FALSE.
You can use an iterator to cycle through all the cookies in the Cookie
collection, or all the keys in a cookie. However, iterating through keys on a
cookie that does not have keys will not produce any output. You can avoid this
situation by first checking to see whether a cookie has keys by using the .HasKeys
syntax. This is demonstrated in the following example.
<%
'Print out the entire cookie collection.
For Each cookie in Request.Cookies
If Not cookie.HasKeys Then
'Print out the cookie string
%>
<%= cookie %> = <%= Request.Cookies(cookie)%>
<%
Else
'Print out the cookie collection
For Each key in Request.Cookies(cookie)
%>
<%= cookie %> (<%= key %>) = <%= Request.Cookies(cookie)(key)%>
<%
Next
End If
Next
%>
To get the value of a cookie, use the Request.Cookies collection. For example,
if the client HTTP request sets animal=elephant, then the following statement
retrieves the value elephant:
<%= Request.Cookies("animal") %>
If an HTTP request sends multiple values for the same cookie, ASP creates an
indexed cookie. Each value is assigned a key; you can retrieve a particular
cookie key value by using the syntax Request.Cookies("name)("key"). For example,
if a client sends the following HTTP request:
animal=elephant&elephant=African
The following script command returns the value African:
<%= Request.Cookies("animal")("elephant") %>
9.3- Some Examples Using Cookies:
9.3.1- Cookies Storing:
The script below demonstrates how to populate a form from a cookie.
<%
response.buffer=true
%>
<html><head>
<TITLE>cookiesform.asp</TITLE></head>
<body bgcolor="#FFFFFF">
<%
ln=Request.Cookies("thatperson")("lastname")
fn=Request.Cookies("thatperson")("firstname")
st=Request.Cookies("thatperson")("state")
%>
<Form action = "cookiesformrespond.asp">
Form with Cookies<p>
Please enter your First Name<p>
<Input NAME="NameFirst" size ="40" value=<%=fn%>>
<p>
Please enter your Last Name<p>
<Input NAME="NameLast" size ="40" value=<%=ln%>>
<p>
Please enter your State abbreviation<p>
<Input NAME="State" MaxLength="2" value=<%=st%>>
<Input type=submit></form>
</body></html>
9.3.2- Cookies Displaying:
The script below demonstrates how to store a cookie that was passed in from the
form.
<%response.buffer=true%>
<html><head>
<TITLE>cookiesformrespond.asp</TITLE></head>
<body bgcolor="#FFFFFF">
<%
l=request.querystring("namelast")
f=request.querystring("namefirst")
st=request.querystring("state")
cookypath="/learn/test"
cookydomain=".www.activeserverpages.com"
cookydie=date+365
Response.Cookies("thatperson")("lastname") = l
Response.Cookies("thatperson")("firstname") = f
Response.Cookies("thatperson")("state") = st
Response.Cookies("thatperson").Expires = cookydie
Response.Cookies("thatperson").Domain = cookydomain
Response.Cookies("thatperson").Path = cookypath
response.write Request.Cookies("thatperson")("lastname") & "<p>"
response.write Request.Cookies("thatperson")("firstname") & "<p>"
response.write Request.Cookies("thatperson")("state") & "<p>"
%>
</body></html>
9.3.3- Cookies Deleting:
The script below demonstrates how to remove a cookie.
<%response.buffer=true%>
<html><head>
<TITLE>cookiesformforget.asp</TITLE></head>
<body bgcolor="#FFFFFF">
<%
cookiepath="/learn/test"
cookiedomain=".www.activeserverpages.com"
cookiesdie=date-365
Response.Cookies("thatperson").Expires = cookiesdie
Response.Cookies("thatperson").Domain = cookiesdomain
Response.Cookies("thatperson").Path = cookiespath
response.write "I will not remember you"
%>
</body></html>
9.3.4- Cookies Simplified –Storing, Displaying &
Deleting - (by Paul Rigor of http://www.mysticpc.com)
A reader of the site submits this simplified cookie reading, writing and
deleting by automatically determing the correct domain and path info without you
having to specify it for each cookie.
<%response.buffer=true%>
<!--#include file="cookielib.asp"-->
<html><head>
<TITLE>cookiesub.asp</TITLE></head>
<body bgcolor="#FFFFFF">
<%
Call AddCookie("Person", "Firstname", "Robert", 365)
Call AddCookie("Person", "LastName", "Forward", 365)
response.write GetCookie("person","firstname")
response.write GetCookie("person","lastname")
%>
</body></html>
Here is the library code that does most of the work:
<%
'=======================================================================
' CookieLib.asp by Paul Rigor (http://www.mysticpc.com)
' online at http://www.activeserverpages.com/learn/cookiesub.asp
' copyright 1998 by Paul Rigor
'
' application("cookiedomain") and application("cookiepath") can be
' set if firewall precludes accurate server variable
'
' AddCookie(Cname, CKey, CValue, CExpDays)
' Example: Call AddCookie("MyCookie", "Cost", "$1.00", 100)
'
' KillCookie(Cname,CKey)
' Example: Call KillCookie("MyCookie", "Cost")
'
' GetCookie(Cname,Ckey)
' Example: Call GetCookie("MyCookie", "Cost")
'
' Cname = Cookie Name: Required, for cookie name
' Ckey = Cookie Key: Optional(empty sting), use if cookie should be a
dictionary
' Cvalue = Cookie Value: Required, what the cookie should be set to.
' CExpDays = Cookie Expiration: number of days cookie is valid, default 365
Function AddCookie(Cname, CKey, CValue, CExpDays)
If Cname = "" Then
Exit Function
End If
If IsNumeric(CExpDays) = False Then CExpDays = 0
If CExpDays < 1 Then CExpDays = 365
If CValue = "" Then CValue = " "
If CKey <> "" Then
Response.Cookies(Cname)(CKey) = CValue
Else
Response.Cookies(Cname) = CValue
End If
Response.Cookies(CName).Expires = Date + CExpDays
Response.Cookies(CName).Domain = GetCookieDomain()
Response.Cookies(CName).Path = GetCookiePath()
End Function
Function KillCookie(Cname,CKey)
If CKey <> "" Then
Call AddCookie(Cname, Ckey, "", 0)
Else
Response.Cookies(Cname).Expires = Date - 365
Response.Cookies(CName).Domain = GetCookieDomain()
Response.Cookies(CName).Path = GetCookiePath()
End If
End Function
Function GetCookie(Cname, Ckey)
If CKey <> "" Then
GetCookie = Request.Cookies(Cname)(Ckey)
Else
GetCookie = Request.Cookies(Cname)
End If
End Function
Function GetCookieDomain()
If Application("CookieDomain") <> "" Then
GetCookieDomain = Application("CookieDomain")
Else
GetCookieDomain = Request.ServerVariables("SERVER_NAME")
End If
End Function
Function GetCookiePath()
If Application("CookiePath") <> "" Then
GetCookiePath = Application("CookiePath")
Else
TmpPath = Request.ServerVariables("SCRIPT_NAME")
TmpPath = Split(TmpPath, "/")
For PathArryCnt = 0 to Ubound(TmpPath) - 1
GetCookiePath = GetCookiePath & TmpPath(PathArryCnt) & "/"
Next
If GetCookiePath = "/" Then GetCookiePath = ""
End If
End Function
%>
|