Search Search

#1 worldwide
FREE Coding Lessons

since 1996
   THE BEST WAY to learn ASP & Asp.net!
Advertise Here!
click for details
Credits Host:
DiscountASP.net
Server Admin:
The "Team"
Contact Info.
Charles M. Carroll

my Blog
[prev. Lesson]  State Management Introduction
     [next Lesson]  Application Data

What are Sessions?

Sessions are a very convenient ASP feature. When someone visits a web page on your site, ASP calls that a "session" and immediately can differentiate that user from all other users at a site. Anything stored in that user's session can be retrieved and manipulated from that page and the next pages they visit, and the data will be tied to that user. 

Session data is generally attached to one user. When a user visits their first page of your site, that page and every page they visit is collectively called a session. Any data attached stored in that session object is private to the pages that user is visiting.

The code to store data in a session variable is simple.  Here we will allow a user to flip a coin, i.e. flipcoin.asp and count their successes:

   filename=/learn/test/flipcoin.asp

<Test Script Below>


<% 
response.write "Coin Tossed!<br>"
randomize
randomnum=int(rnd*2)+1
IF randomnum=1 THEN
    session("heads")=session("heads")+1
ELSE
    session("tails")=session("tails")+1
END IF
response.write "Heads= " & session("heads") & "<br>"
response.write "Tails= " & session("tails") & "<br>"
%>

Even though there are many people at the site they all have different scores for their "heads" and "tails" count. They each has a session and it co-ordinates and differentiates their values.

A much more practical example could protect access to a page based on a session variable that indicated their security level determined once upon login, see:
http://www.learnasp.com/freebook/asp/security.aspx

Some basic things should be noted:

  • Session data is stored on the server, not in cookies. No user could examine the session cookie and determine the contents of any session variables.

  • A cookie is used to co-ordinate the user's session ID. Once again the cookie contains no data (just the session ID). This means if the user accepts no cookies, you can't use sessions as described here.

  • If you absolutely need sessions without client cookies, installing an ISAPI filter named "Cookie Munger" will solve your problem, but at a performance penalty.
    http://msdn.microsoft.com/workshop/server/toolbox/cookie.asp

Chaz Wish List
Tall Tip $5
Grande Tip $20
Venti Tip $39
Tip Jar Thanks
2004 Thanks
2005 Thanks
HUGE Tip -love site