What Are Cookies and Sessions, and How Do They Relate to Each Other

What are cookies and sessions, and how do they relate to each other?

Let's go through this:

Cookies and sessions are both ways to preserve the application's state between different requests the browser makes. It's thanks to them that, for instance, you don't need to log in every time you request a page on StackOverflow.

Cookies

Cookies are small bits of data, (maximum of 4KB long), which hold data in a key=value pairs:

name=value; name2=value2

These are set either by JavaScript, or via the server using an HTTP header.

Cookies have an expiry datetime set, example using HTTP headers:

Set-Cookie: name2=value2; Expires=Wed, 19 Jun 2021 10:18:14 GMT

Which would cause the browser to set a cookie named name2 with a value of value2, which would expire in about 9 years.

Cookies are considered highly insecure because the user can easily manipulate their content. That's why you should always validate cookie data. Don't assume what you get from a cookie is necessarily what you expect.

Cookies are usually used to preserve login state, where a username and a special hash are sent from the browser, and the server checks them against the database to approve access.

Cookies are also often used in sessions creation.

Sessions

Sessions are slightly different. Each user gets a session ID, which is sent back to the server for validation either by cookie or by GET variable.

Sessions are usually short-lived, which makes them ideal in saving temporary state between applications. Sessions also expire once the user closes the browser.

Sessions are considered more secure than cookies because the variables themselves are kept on the server. Here's how it works:

  1. Server opens a session (sets a cookie via HTTP header)
  2. Server sets a session variable.
  3. Client changes page
  4. Client sends all cookies, along with the session ID from step 1.
  5. Server reads session ID from cookie.
  6. Server matches session ID from a list in a database (or memory etc).
  7. Server finds a match, reads variables which are now available on $_SESSION superglobal.

If PHP does not find a match, it will start a new session, and repeat the steps from 1-7.

You can store sensitive information on a session because it is kept on the server, but be aware that the session ID can still be stolen if the user, let's say, logged in over an insecure WiFi. (An attacker can sniff the cookies, and set it as its own, he won't see the variables themselves, but the server will identify the attacker as the user).


That's the gist of it. You can learn more on the PHP manual on both subjects.

Cookies vs. sessions

The concept is storing persistent data across page loads for a web visitor. Cookies store it directly on the client. Sessions use a cookie as a key of sorts, to associate with the data that is stored on the server side.

It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.

Edit: I don't think there is any advantage to using cookies, other than simplicity. Look at it this way... Does the user have any reason to know their ID#? Typically I would say no, the user has no need for this information. Giving out information should be limited on a need to know basis. What if the user changes his cookie to have a different ID, how will your application respond? It's a security risk.

Before sessions were all the rage, I basically had my own implementation. I stored a unique cookie value on the client, and stored my persistent data in the database along with that cookie value. Then on page requests I matched up those values and had my persistent data without letting the client control what that was.

Relation between sessions and cookies

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.

Difference between Session Cookies and General Cookies?

This is an implementation detail of the website, so this can't be directly answered.

The session cookie may be created server side and associated with the saved session, but it still has to be saved client side so that the client browser can remind the server which session to use (and verify it).

From the browser's perspective, there is no difference between a session cookie and any other cookie. It's just a cookie. So there's no technical reason why all the cookies can't coexist as long as there are no name collisions.

From the web server's perspective, if the non-session cookies had a purpose, that purpose is likely still there when there is a session, so deleting them to use the session in its place would probably just make the code more complex. But this doesn't say if they will or won't do that.

So, another way to ask the question would be "Are the authors of the website going to be lazy and not bother deleting redundant cookies, or are they going to be fancy and merge them into the session and clean things up?"

Also consider the session cookie and the other cookies may all have different lifetimes, so it might not make sense to merge them anyway.

Are session and cookies the same thing?

In each HTTP response, the server has the opportunity to add a header Set-Cookie: {cookie-name}={cookie-data}; {cookie-options}.

The browser will, in every subsequent HTTP request (or as specified by the options), add a header Cookie: {cookie-name}={cookie-data}.

Request #1:

POST /auth/login HTTP/1.1
Host: www.example.com

username=Justice&password=pass1234

Response #1:

HTTP/1.1 307 Temporary Redirect
Set-Cookie: user_id=928
Location: http://www.example.com/dashboard

Request #2:

GET /dashboard HTTP/1.1
Host: www.example.com
Cookie: user_id=928

Response #2:

HTTP/1.1 200 OK
Content-Type: text/html

<html>
<head>...</head>
<body>...</body>
</html>

All future requests will also include the Cookie header.

What is the difference between Sessions and Cookies in PHP?

A cookie is a bit of data stored by the browser and sent to the server with every request.

A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)

What are sessions? How do they work?

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.

Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request.
However they are not good in case you don't want that data to be readable/editable on client side.

The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.

Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.

In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.



Related Topics



Leave a reply



Submit