ASP Session Variables
Session variables let ASP store data on the server for one specific visitor, and that data stays available across every page the visitor requests until their session ends.
What Is a Session?
When a visitor first requests a page from an ASP application, the server creates a Session object just for them and assigns it a unique Session ID. That ID is sent to the browser as a single small cookie. On every later request, the browser sends the ID back, and ASP uses it to look up that visitor's own private storage area on the server, called Session variables.
Storing a Session Variable
<%
Session("username") = "Priya"
Session("cartTotal") = 0
%>Reading a Session Variable on Another Page
Example
<%
If Session("username") <> "" Then
Response.Write "Hello, " & Session("username") & "!"
Else
Response.Write "Please log in first."
End If
%>Cookies vs. Session Variables
It is easy to confuse cookies and Session variables because a Session relies on a cookie behind the scenes, but the two store data very differently. A cookie stores the actual data on the visitor's browser. A Session variable stores the actual data on the server; the browser only ever holds a small session ID cookie pointing to that server-side storage.
Controlling How Long a Session Lasts
By default, IIS ends a session after 20 minutes without a new request from that visitor, freeing the server memory it used. You can change this per session with Session.Timeout, measured in minutes, and end a session immediately with Session.Abandon.
Session Timeout and Abandon
<%
' Keep this visitor's session alive for 45 minutes of inactivity
Session.Timeout = 45
%>
<%
' On a logout page, end the session right away
Session.Abandon
Response.Redirect "login.asp"
%>Exercise: ASP Session
What is the scope of a Session variable?