Cookies and Session are used to make a stateful communication between client’s system and server, or it can be between computers.
When a client sends a request to a server, an HTTP request is created with a header consisting of information about the user and requested page.
In a similar way, when the server provides the appropriate page back to the client, an HTTP response is generated with a header having information about the document being sent.
In an all, HTTP protocol is used for communicating on the web.
This HTTP protocol is stateless and to make it stateful, we use Cookies and Session.
Difference between Cookies and Session in Tabular form
Cookies | Session |
---|---|
It is a small piece of information which is sent by the server on the client's machine to identify a user uniquely | It is a set of data that is stored on a server |
It expires after a specific length of time | It expires as and when the browser is closed |
It is not secured as one can read values and may alter them directly by accessing and reading it from browser | It is more secure as it is managed and stored at server-side |
The size of the cookie is limited to 4 kb | The storage capacity of Session is comparatively more than cookies |
A user can disable cookies | A user can't disable session |
Session
A session is used to provide stateful communication between client and server. It maintains the state by storing the information at the server side.
It assigns a unique session ID to every user at first visit on the website and the same session id is saved at the client’s machine in the cookies.
Cookie
At the client level, Cookies are the small piece of information which is sent by the server to identify the user and its activities uniquely.
In this method, the information is stored locally on the user’s browser and later on, this information is then being sent to the server whenever the information is needed ( when the user again visits that site).
How do cookies and session work?
When a client’s computer requests a webpage from a server ( a Website), in return, the server answers back with the requested webpage. This is how client/server approach works.
However, it is crucial to keep information about users in order to monitor the behavior carried out by them on various webpages. This can be done by maintaining state.
As it helps in the further development of complex interactive web-based applications.
If a server isn’t capable of maintaining the state then it would forget all the information about a visitor and the page on which he landed on, as and when it responded.
To overcome this problem, this type of information is stored on the server itself or the user’s browser locally. One of the way is cookie and session.