ASP CookiesCollection
Complete Request Object Reference
The Cookies collection is used to set or retrieve the value of a cookie. If the cookie does not exist, it creates it and assigns it the specified value.
Note:The Response.Cookies command must be placed before the <html> tag.
Syntax
variablename=Request.Cookies(name)[(key)|.attribute]
| Parameters | Description |
|---|---|
| name | Required. The name of the cookie. |
| value | Required (for the Response.Cookies command). The value of the cookie. |
| attribute | Optional. Specifies information about the cookie. Can be one of the following parameters:
|
| key | Optional. Specifies the key where the value is assigned. |
Examples
The "Response.Cookies" command is used to create a cookie or set the value of a cookie:
Response.Cookies("firstname")="Alex"
%>
In the above code, we created a cookie named "firstname" and assigned it the value "Alex".
You can also set properties for the cookie, such as setting the expiration time of the cookie:
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2002#
%>
Now, the value of the cookie named "firstname" is "Alex", and its expiration date on the user's computer is May 10, 2002.
The "Request.Cookies" command is used to retrieve the value of a cookie.
In the example below, we retrieve the value of the cookie "firstname" and display it on the page:
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
Output:
A cookie can contain a multi-value collection. We call this the cookie having keys.
In the example below, we will create a cookie collection named "user". The "user" cookie has keys that contain information about the user:
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
The following code reads all cookies that the server has sent to the user. Note that we used the HasKeys property to determine whether the cookie has keys:
<body>
<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br>")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br>")
end if
response.write "</p>"
next
%>
</body>
</html>
%>
Output:
user:firstname=John
user:lastname=Smith
user:
country=Norway
user:
age=25
Complete Request Object Reference Other Extensions