Sessions and Cookies


 

The Session object is used to store and change information about a user session. Variables stored in the Session object hold information about one single user, and are available to all pages in one application.

 

Using Session objects:

 

<%
Session("username")="Donald Duck"
Session("age")=50
%>

 

<%

Session("username")="Donald Duck"

Session("age")=50

 

dim i

For Each i in Session.Contents

  Response.Write(i & "<br />")

Next

%>

 

Result:

 

username

age

 

If you do not know the number of items in the Contents collection, you can use the Count property:

 

<%

dim i

dim n

n = Session.Contents.Count

Response.Write("Session variables: " & n)

For i=1 to n

  Response.Write(Session.Contents(i) & "<br />")

Next

%>

 

Result:

 

Session variables: 2

Donald Duck

50

 

Cookies

 

There is a problem with identifying a user in case a user repeatedly checks in a Web site.

 

Problem: the Web server does not know who the user is and what you do because the HTTP address doesn't maintain state.

 

ASP solves this problem by creating a unique cookie for each user. The cookie is sent to the client and it contains information that identifies the 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. ASP can both create and retrieve cookie values.

 

Creating a Cookie

 

The Response.Cookies command is used to create cookies.

 

Note: The Response.Cookies command must appear BEFORE the <html> tag.

 

<%

Response.Cookies("firstname")="Alex"

%>

 

It is also possible to assign properties to a cookie, like setting a date when the cookie should expire:

 

<%

Response.Cookies("firstname")="Alex"

Response.Cookies("firstname").Expires=#May 10,2002#

%>

 

Retrieving a Cookie Value

 

The Request.Cookies command is used to retrieve a cookie value.

 

<%

fname=Request.Cookies("firstname")

response.write("Firstname=" & fname)

%>