Cookies Vs. Sessions

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.

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 localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

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.



Related Topics



Leave a reply



Submit