Cookies and Sessions are used to store information to “remember” activities engaged with the users. Cookies are only saved on the client-side machine, while sessions are stored on the server.
A session generates a text file in a temporary directory on the server where registered session variables and their values are stored. Users have no access to session files since they only live on the server.
A cookie is a text file that the web browser lives on the client’s local computer that stores a unique identification number as the session ID and any other data in key:value pair format. The maximum size of a cookie file is limited to 4KB.
Set-Cookie: name2=value2; Expires=Wed, 19 Jun 2031 10:18:14 GMT
Above causes the browser to set a cookie named name2 with a value of value2, which would expire in about ten years, assuming it is the year 2021.
The next time the browser sends any request to the web server, it will include that information stored in the cookies, and the server will use that information to identify the user.
When a Session Ends
A session ends when the user closes the browser or after leaving the site. If you delete the cookie in the browser, the connection to that session is also lost.
Why Cookies At All??
The World Wide Web runs on HTTP (Hypertext Transfer Protocol), a “stateless” protocol, to transfer information between networked devices. Been stateless means that each command runs independently without any knowledge of previous ones.
Being stateless is an essential design principle of HTTP to preserve precious server resources and maximize client connections.
Cookies and sessions work hand-in-hand to preserve the application’s state between different requests the browser makes. They are necessary workarounds that make the World Wide Web “stateful” again. Thanks to them, you don’t need to log in every time you visit a page on Facebook.