Cookies Handling in ASP

This section contains the codes and resources related to Classic ASP and ASP.net languages.

Cookies Handling in ASP

Postby Shahzad Butt on August 15th, 2008, 3:47 am

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With ASP, you can both create and retrieve cookie values.

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
Regards
Shahzad Butt
http://www.GeoSourceCode.com
Shahzad Butt
 
Posts: 24
Joined: July 9th, 2008, 11:16 am
Location: Pakistan

Return to ASP / ASP.net

Who is online

Users browsing this forum: No registered users and 0 guests

cron