I learned about the difference between SESSION
and COOKIE
but I am trying to find the relation between the two. I checked on multiple sites but couldn't get a relevant answer for this and left confused. Are the cookies generated on the user's browser or the system? Some say it gets generated on the system whereas some other links said they get created on the user's browser. Also sessions get saved in the form of cookie or cookie file. Is that true?

- 117
- 1
- 1
- 14
-
See also: [What is the difference between Sessions and Cookies in PHP?](http://stackoverflow.com/q/6339783/759866) Note that the same concept applies to any programming language. – BenMorel Sep 14 '15 at 13:32
4 Answers
Cookie
A cookie is just a key-value pair that is stored in the user's browser. A cookie is sent to your browser as part of the HTTP response that contains the web page you requested.
When your browser receives a cookie, it stores it, and sends it back to the server with every subsequent request it makes on the same website.
Because cookies are part of the HTTP request and response headers, they are somewhat limited in size.
Typical information stored in cookies:
- Session IDs (see below)
- Tracking IDs (Google Analytics, etc.)
- User preferences (preferred language or currency, etc.)
For larger, or sensitive data, you typically store values in the session. The cookie is only there to identify the proper session.
A cookie can be configured to only live until the browser window is closed, or have a configurable lifetime (1 week, 1 month, 1 year, whatever). If you visit the website again during this period, your browser will send the cookie with every request.
Session
A session is a set of data that is stored on the server, usually as key-value pairs. A session is assigned a pseudo-random, secret ID that is usually stored in the user's browser using a cookie, for example SESSID=abcdef123456789
. The session ID typically matches the name of a file containing the session data on the server.
Sessions are usually short-lived, and automatically deleted if unused for some time (20 minutes or so).
Typical information stored in a session:
- ID of the user currently logged in
- Shopping cart
- ... anything you can think of, that can be safely deleted when the session expires
Example
Let's say I visit a website for the first time. The website detects that I didn't send a session cookie, so it creates a session for me. It creates a session file on the server, such as /tmp/sess_abcdef123456789
.
Then it sends a cookie header with the HTTP response that contains the web page:
HTTP/1.1 200 OK
Set-Cookie: SESSID=abcdef123456789
My browser stores this cookie. If I visit another page on the same server, my browser will send this cookie with the request:
GET /cart HTTP/1.1
Cookie: SESSID=abcdef123456789
When receiving the second request, the server can check if there's a session file with this ID, and use it to retrieve the session data.
Your web programming language will offer support for sessions, and should handle most of this complexity for you. You can usually directly use the session array/object, which will be already populated with the session data specific to the user visiting your website, and will be automatically saved if you update the session data; this should be totally transparent to you.
Security
When logging in a user to your website, always store the user ID in the session. Never trust a user ID stored in a cookie to load user data.
It's very easy to forge a cookie. If you were to load user information based on a user ID stored in a cookie, it would be easy to change the user ID in this cookie to gain access to any user's account on your website.
On the other hand, if you store the user ID in the session, which is assigned a pseudo-random session ID, it will be hard for an attacker to guess the session ID that is currently assigned to the user.

- 34,448
- 50
- 182
- 322
-
"Sessions are usually short-lived, and automatically deleted if unused for some time (20 minutes or so)." Lets say I am using gmail account and close the browser without logging out, come back again later after a long time. It does not ask me for login again. On the other hand if I am using Cpanel for database purposes and if I am not active for a certain time it automatically gets logged out. How does session play their part in such cases? – P Singh Sep 14 '15 at 12:00
-
I can only emphasize the *usually*: nothing prevents you from writing a long-lived session handler, which Gmail is probably doing in some way. OTOH, Cpanel probably uses a typical, short-lived session handler, with a garbage collector that automatically cleans up sessions that have not been used for more than say, 20 minutes. This is the kind of session you get out-of-the-box with your programming language of framework. – BenMorel Sep 14 '15 at 13:06
-
1I've personally been implementing long-lived sessions ("stay connected" checkbox) with two separate sessions for each user: a short-lived session that contains the logged-in user ID, shopping cart, etc., and a long-lived session that only contains the user ID. I first check the short-lived session if a user ID is present. If it is not, then I check the long-lived session, and if a user ID is there, I log in the user again by copying the user ID into the short-lived session. That way, I do not keep forever temporary data such as shopping carts, but I do keep the user ID for a long time. – BenMorel Sep 14 '15 at 13:07
-
Pretty cool. Thanks for the idea, I may use this sometime in the future. – P Singh Sep 14 '15 at 13:15
-
@PSingh By the way, I just added some security considerations regarding login to my answer. – BenMorel Sep 14 '15 at 13:24
-
Thanks for the update, I recently learned the same about getting access to user's secured data through cookie which is quite tricky through sessions. Will be taking care of this in my future modules. – P Singh Sep 14 '15 at 13:29
-
@Benjamin Just one query, in amazon my shopping cart always have my stuff, how does that happen. Thanks – Suraj Jain Dec 29 '17 at 12:00
-
@SurajJain That could be an implementation of a long-lived session, however in the case of Amazon, the cart is likely stored in the database, not in the session, and tied to your user id, not to your session id. This way, the cart survives login/logout and is available on every device you connect from. – BenMorel Dec 30 '17 at 10:26
-
-
sorry, could ypu please clarify: "When logging in a user to your website, always store the user ID in the session. Never trust a user ID stored in a cookie to load user data."... it looks to me that however the server stores the userID, the user always sends userID/sessionID as a cookie? .. or not always? – Andrey M. Stepanov Jan 16 '19 at 22:02
-
@AndreyM.Stepanov The user always sends the **session** ID as a cookie, not the **user** ID. The session ID is usually a long, obscure, random alphanumeric string that's unique to the visitor and cannot be guessed by an attacker. The server associates the user ID to the session ID. When a visitor sends a session ID cookie that is known to the server, the server can trust that the visitor *is* the user whose ID is contained in the session. If the server was to trust a user ID directly sent in a cookie, anyone could use everyone's account by just sending a forged cookie. – BenMorel Jan 16 '19 at 23:32
-
@Benjamin Thank you for the answer. Does it mean that userId is typically stored as session variable or there is no need for the server in any user identifier other that session ID? – Andrey M. Stepanov Jan 17 '19 at 10:47
-
@AndreyM.Stepanov Indeed, the user ID is typically stored as a session variable. – BenMorel Jan 17 '19 at 11:21
-
@Benjamin So what i understood is that we should store the user Id with the session ID so that when a user tries to log in then the cookieID is matched with the this session Id present on the server and if that matches, then we should compare the userId of the session and of the cookie because someone can edit this userId in the cookie. And if just blindly let the user log into the website with the userId present in the cookie then he can get logged in with someone else’s account given that he changed the userId in the cookie. Did I get it right? – asn Jan 28 '20 at 23:43
-
@Benjamin Also is the sessionId updated on every log-in activity of the user? If yes, then Shouldn't the cookie Id be updated too? – asn Jan 28 '20 at 23:49
-
@ajaysinghnegi I think you got that right. Usually you get a new session ID on every login, or every visit of the website. Typically, the session ID is sent over a "session cookie" (a cookie with no expiration timestamp; unfortunate naming), which is deleted as soon as you close the browser. And the session expires after a given delay, say 20 minutes with no activity. So every time you get assigned a new session, you get a new cookie, too. – BenMorel Jan 29 '20 at 08:29
I found this link which explains the relation between cookies and sessions regarding persistence and load balancing servers. It basically talks about how if your session is with one server and you get redirected, the cookies will store relevant session information like the session ID so that you can have persistence across all servers.
https://devcentral.f5.com/articles/sessions-and-cookies-and-persistence-oh-my#.UdPNRGfYhOY
The link explains it a lot better than I can.

- 139
- 1
- 9
-
-
Yep, persistence, load balancing, sessions and cookies are all related. You should come across these terms often. – KNN. T Sep 14 '15 at 11:46
-
Session unlike cookie stores the data on the server. However, session information is stored in the user cookie
Session uses cookies to store information about yourself in the user's browser. For example cookie SSID contains a session identifier, for which the server will understand what kind of session is tied to this user

- 113
- 1
- 7
-
I didn't understand by this - "the server will understand what kind of session is tied to this user", are there session types that gets created for a user? If yes what are they? – P Singh Sep 14 '15 at 11:15
-
The server, depending on realizaii himself associated with the session cookie. Session itself is stored in memory or on disk (also depends on the implementation). When a request to the server, he takes from the request required cookie and ties her existing session. If not, it creates a new one. – Cobalt Sep 14 '15 at 11:25
-
-
The COOKIE resides on the client, i.e. the browser. The COOKIE is automatically passed with the request to the server, where the server uses the cookie to fetch any SESSION data that the server has stored for that client.

- 11
- 1
-
-
No, usually the cookie contains the Session ID. The session data will be stored on the server. – askotte Sep 14 '15 at 11:50
-