What is a session?
A session is a specific period of time for communication between two devices, two systems, or two parts of a system.
Why are sessions important?
Track a user’s (client) activity
Suppose a user opens a website and login to the website, so the user’s current state is logged in.
What if the website does not track or remember the user’s current state, then the user will need to log in every time when the user requests a page.
There are many situations where you need to complete a phase and then you can move on.
Here is one more example of a simple shopping cart – In the following image you can see there are 6 steps (user states) to place an order, and each step (user state) is related to the previous one, so you have to preserve each state.
There are some ways to preserve the states and two of them are the most popular which are cookie and session.
Cookie VS Session
- Cookie – Cookies are used to save pieces of information inside a client (local computer).
- Session – Sessions are used to save information on a server.
|Cookies store data in a text file on the client-side computer.||Whereas session stores data on a server in encrypted form.|
|It can only store a certain amount of data (the maximum size of the browser’s cookies is 4 KB).||In a session, we can store an unlimited amount of data, but there is a maximum amount of memory that a script can use at once, which is 128 MB.|
|Cookies do not expire until you set an expiration time or clear the browser’s cache.||User session end when they log out or close their web browsers.|
Which one is better?
Both are good but the session is better when it comes to storing sensitive information because the information is stored on a server in encrypted form.