How to Create a Cookie?
The "Response.Cookies" command is used to create cookies.
Note: The Response.Cookies command must appear BEFORE the <html> tag.
In the example below, we will create a cookie named "website" and assign the value "Geo Source Code" to it:
- Code: Select all
<%
Response.Cookies("website")="Geo Source Code"
%>
It is also possible to assign properties to a cookie, like setting a date when the cookie should expire:
<%
Response.Cookies("website").Expires=#January 01,2009#
%>
How to Retrieve a Cookie Value?
The "Request.Cookies" command is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "website" and display it on a page:
- Code: Select all
<%
website=Request.Cookies("website")
response.write("My Website Name is " & website)
%>
Cookie with Keys
If a cookie contains a collection of multiple values, we say that the cookie has Keys.
In the example below, we will create a cookie collection named "user". The "user" cookie has Keys that contains information about a user:
- Code: Select all
<%
Response.Cookies("user")("firstname")="Shahzad"
Response.Cookies("user")("lastname")="Butt"
Response.Cookies("user")("country")="Pakistan"
Response.Cookies("user")("age")="26"
%>
Look at the following code to read all the cookies:
- Code: Select all
<html>
<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=Shahzad
user:lastname=Butt
user:country=Pakistan
user:age=26