How Session Work in Web Applications and Why We Need It

Term 'Session' is used in different contexts in computer science e.g. connection, telnet session, session layer, web session, etc. I would discuss the sessions in context of web applications only. There are following fundamental points related to sessions in web applicaitons:

1. What is a session in web application?
2. Why we need a session?
3. How session creation and identification work?
4. Where session data is stored?
5. How to Delete a session?

Lets look at each part one-by-one:

1. What is a Session in Web Application?

Web developer may need to store small data temporarily at server side, for each user who is interacting with the web application. Such data is stored in a session, so session is a temporary storage at web server. For each user, there is unique session are at server. During request processing of a particular user, the user's session is accessable in all web pages i.e. data stored in session by index.php can be accessed by products.php or any other page. Session data is stored in key/value form where key is string and value can be any object. Its a data structure like associative-array in PHP or map/hashmap in Java i.e. you save values against some keys.

The important point is, session is unique for each user. If there are 10 users interacting with the server, there would be 10 sessions created at server side (we would shortly see how it is created), one for each user. Below picture explain this idea; there are 3 users i.e. U1, U2, U3 interacting with the web-server, so there are 3 sessions at server side, one for each user i.e. S1 for U1, S2 for U2 and S3 for U3.

If we save data in session for U1, it would be stored in S1 bucket or session. When we would get data for U1, it would be automatically read from S1 session. (Later I have explained how server keep track of which session bucket, belong to which user. In same way, data stored for U2 goes in S2, and so on.

In PHP, session data is stored in a file at server side, separate file is created for each session. Web developer do not read or write data from this file directly but built-in methods are used for reading and writing data and to create new sessions. How session is created, how data is added and retrieved back is explained in point 3 below.

2. Why We Need a Session?

HTTP is a stateless protocol. When a user request some URL, web-server serve the requested page and closes the connection (i.e. TCP socket between browser and web-server is closed). From server perspective, each request is unique and isolated from previous requests. By closing the connection after each request, server can serve more users with same resources (processing capacity, main memory, etc.). If server do not close the connection, some server resources would be kept occupied as long as the web page is open in browser.

Sometime web developer need to identify who made a particular request to serve personalized contents to the user. Now I explain some scenerios, it would help you to understand different types of data that we may need to store in session:

Session Usage Example 1. Once user is logged-in successfully, we want to keep record that user has logged-in so that, user requests to secure pages e.g. dashboard.php or profile.php, could be served without asking user to login again. We may need to show logged-in user-name on secure pages. When user login, we store the user-name into session, in subsequent requests, we can check, is the user-name exist in session, that means, the user has logged in and user-name can be accessed from session to show on some page.

Session Usage Example 2. E-commernce websites display list of products user recently visited to facilitate user in revisiting. We can store list of products user visited, in session. For example, whenever user open a product page passing some product ID, we can store that product ID in session. On each request, we can fetch all products IDs user recently visited and show those products' names and pictures (fetching from database based on product IDs).

Session Usage Example 3. Assume a multi-page form, Page 1 shows a form to get personal information, page 2 takes educational detail and page 3 takes family informatin. The application is complete only when user has filled all three forms. So such scenerios, we may store page 1 and page 2 submitted data into session, when user submit page 3, we can get page 1 and page 2 data from session and page 3 data from submitted HTTP request, and store all data into database in one insernt statement. You see, session help us to track the user accross the requests (in next section, I would explain how a unique session is identified even when there are thousands of active session at server).

Session Usage Example 4. We may use session to store list of products and their quantities that user has added into the a shopping cart. Becasue this data is also temporary until user confirm the order. When user confirm the order, we can move data from shopping cart to database e.g. in orders table. If user do not confirm order, the data stored in session would be automatically moved, when user would not ineract with server for some time.

3. How Session Creation and Identification Work?

Now I explain session creation and identification workflow in detail using very basic ordered steps. Below figure explains the steps involve using numbered labels. After the figure, I have explained what action is performed in each step. (I have used PHP vocabulary in explanation, but you shall understand the workflow no matter which language you are using, the flow remains same)

  1. Sessions are created in response to some user request. So, when User 1 send Request 1 to server, the requested page creates a new session by calling session_start() method. As result, a session is created at server side (represented using a square on bottom left of web server figure). A unique session ID is generated, lets assume its 'S1' (in reallity, session id is long alphanumeric string). I have stored user name in the session under 'user' key using PHP i.e. $_SESSION['user'] = 'Ali'. In same way, we can put more data into session array. 
  2. When a new session is created, session_start() method also stores the session ID in HTTP response in Set-Cookie header. The cookie name used by PHP is PHPSESSID, so Set-Cookie:PHPSESSID=S1 is stored in HTTP response packet. So that it could be sent to browser.
  3. When web browser receive an HTTP response that contain Set-Cookie header, it creates a new cookie on user computer. At this stage, PHPSESSID=S1 is stored in browser cookies.
  4. When User 1 send Request 2 to some page, browser automatically add PHPSESSID cookie in HTTP request packet under Cookie header i.e. Cookie:PHPSESSID=S1 
  5. When server receive PHPSESSID cookie with S1 value, session_start() method loads data stored against S1 ID into $_SESSION array. The web page may retrieve earlier stored data or add new data into $_SESSION array.
Please note, we just need to place our data into $_SESSION array, its server responsibility to write this array at block storage and reloading the array when a new request comes from same user (using session ID cookie).

Cookies are stored in browser, so the user may remove them anytime from the browser. As web deverloper, we can't gurantee the cookies created earlier would sure reach at server in subsequent requests. So we should write code considering such possibilities.

4. Where the Session Data is Stored?

From above details, it follows the session data is stored on web server. Only session ID is sent to browser, that is sent back to server using cookie, so that the particular session could be identified at server.

5. How to Delete a Session?

If we want to remove all data stored in session, we can call session_destroy() method. This method shall be called after calling session_start() method, so that, the exisitng session data is loaded into $_SESSION array. After the session_destroy() method is called, all keys and values stored in session are removed and the file stored on disk is also removed. If you are using WAMP for development, you can see these files under: wamp\tmp folder.

Part 2 of contains working code samples with output, for different functions we may need to perform on sessions.


  1. Simple yet effective explanation. Thanks! :D

  2. Detailed explanation. Thank you !

  3. thanx.. that's very simple explanation

  4. More than awesome. With love from referred by Asif Shahzad

  5. Thanks. It was very helpful.

  6. great explanation on a beginner level..... thanks...

  7. Thank you for the clear explanation. I particularly like the way you see a session as a map. Very helpful.

  8. i love this explanation it makes me want to go milk a full stack leprechaun.

  9. Thank you, good job, without unneeded complications :)

  10. Thanks for the straight forward explanation. It helps to demystify Sessions. One question: where in memory is the session typically stored on the server? Main memory would be OK for a small site that need only handle perhaps a thousand sessions concurrently but what happens when there are many thousands of concurrent sessions? Can sessions be easily linked to a database? Thanks again.

    1. Yes, sessions can also be stored in DB or files. Usually its done when user shows no activity for some time but we don't want to sign-out or destroy her session. Sessions synchronizations is another issue, for example 10 servers are serving requests, the first request was served by Server 1, but then it got busy in other users, and the subsequent request from same user sent to Server 4. Now the session data exist in Server 1, so intelligent techniques are used here to make sure sessions remain synchronized on all servers or same server handle the request. It latest web architectures, e.g. SOFEA, its is recommended that server always remains stateless and any data that need to be stored in session should be maintained at client/browser side. The details of these issue is out of scope of this post.

    2. Yes it is possible but you get a overhead when storing in DB, so its batter to do only for inactive users as very well explained by Asif

    3. Thanks for clear my concept.....

  11. Nice one.. great stuff :-)

  12. I have a simple form submission. It stores some fields in the database. will that require session usage? if i do not use then? please somebody suggest as how and where to use the session code. thanks

  13. thanks sir, it makes my day... :)

  14. Still useful after many years, thank you for sharing


Post a Comment