ASP: the session object (vs cookies)

I've been talking about cookies some time ago, however you should know there's another way of storing information if you use ASP: the session object. There's a big difference between cookies and sessions: cookies are client-side, while sessions are server-side. When we open an ASP page, the server creates an unique identifier that will determine the session id. While cookies can have a long expiration time, usually sessions have a predetermined timeout (20 minutes). Cookies are completely controlled by the code of the page and can be created, changed and destroyed using appropriate commands - as we saw in the aforementioned article. That is true for sessions as well, however the session unique identifier is always created when an ASP page is opened. By default, when an ASP request is made to the server, the session is automatically started and the unique identifier is stored for future use. The session ends after 20 minutes by default (it's possible to change that value programmatically or in IIS).


The session
The session is created when we open an ASP page - as said. Upon session opening, a cookie is created client-side with the session id. Something similar to:
Cookie: ASPSESSIONID=PUYQGHUMEAAJPUYL
That cookie has no expiration date, meaning that it will be flushed when the user exits the browser. At the same time, the created session will expire in 20 minutes by default - as said - if the page is not refreshed or if a new request is not made.
We can change the session timeout using:
<%
Session.Timeout=5
%>
The value is expressed in minutes (5 minutes). And use the Abandon method to end the session:
<%
Session.Abandon
%>
The session object supports an array that can be used to store information.

How to store information
The way we store information in the session object is very similar to the way we do it with cookies. For example, we can store the user name and the gender:
<%
Session ("username") = "Denny Crane"
Session ("gender") = "Male"
%>
And then, display those information:
Hello <%= Session("username")%>
We know you are <%= Session("gender")%>
Simple as that! As you can see, sessions work like cookies.

Remove information
To remove the stored information, we can use the following code:
<%
Session.Contents.Remove("username")
%>
Or remove all the info:
<%
Session.Contents.RemoveAll()
%>

All the above can be used in the global.asa file on the server, to control what's happening on session start and end. I will probably write something about it in the near future.

And that is all. See you next time and have a splendid summer day!