In this tutorial I'll explain what cookies and sessions are, and why we need them. In order to get the most out of this lesson, it's best that you have an understanding of the Request/Response cycle.

Why We Need Cookies and Sessions

HTTP is stateless. When you make a request, the request is sent to the server and then the connection is terminated. When the response is sent back, it is sent from the server to the client, and the connection is again terminated. HTTP doesn't "remember" anything about previous requests and responses: When you click a link on a page, the server doesn't remember any of your previous requests or information about those requests. This is unlike FTP (File Transfer Protocol, which you might have used if you've ever uploaded/downloaded files using a client such as FileZilla or CoreFTP), which is stateful. FTP maintains the connection between the client and the server and keeps track of state information about the connection.

server doesn't remember you between request/response cycles
HTTP is Stateless: the server doesn't remember you between request/response cycles

The problem with a stateless protocol like HTTP is that you (as a developer) often need to keep track of information about the user/client between requests. For example, if your site is an online store, you need to keep track of what items the user adds to their shopping cart as they navigate from one page to another. Each time the user requests a new page, how does the server "remember" what items the user already had in their cart?

One way to remember this kind of information is by using cookies. Cookies can only store small amounts of text data. Additionally, many more savvy users block cookies in their browser, as a privacy measure.

Another option many developers prefer are sessions. Sessions can store larger amounts of data, and even different kinds of data (entire objects or lists, for example). However, when you have many users using your web app at once, your server can quickly become overloaded with large amounts of session data.

What are Sessions?

Sessions are a way to store more data, or more complex data on the server as a way of "remembering" user data between request/response cycles. Sessions are a bit more complex than cookies: in fact, sessions actually use cookies as part of their funcionality.

A session is a visit to a web site or application: A session consists of a user first loading your site/application, using and/or navigating around the site/application, and then leaving the site/application.

A Session begins when a user accesses your application (any page, generally). A Session ends when one of the following happens:

  • The session times out. A session times out after 30 minutes of no activity, when there are no new requests made with a specific session ID. The timeout value of 30 minutes can be changed programmatically in your application.
  • Your code invalidates or destroys the session. For exmaple, you might write code that destroys the session when a user logs out.
  • The application or server shuts down or restarts.

When a Session is first created, a unique session ID is generated for that session. The server stores the session ID along with any other user data that was included in the request. The server then sends the session ID back to the client in the response. The client reads the session ID and stores it in as a session cookie.

new session starts when request is first made, server generating a unique session id, sending it back to client in the response
The server generates a unique session ID which is stored as a session cookie on the client machine

For the next request, and all subsequent requests, the session id stored in the session cookie is sent along in the request object. The server then reads the session ID in the request and matches it to table of session data it has: the session data with the same session ID belongs to that specific user during this current session. Any new data can be added and associated with that same session ID as needed.

the second and subsequent requests sending the session id to the server, server looks up the session id to access stored user data
Every request sends the session ID to the server so the server can look up the user's stored data for that session.

When the session expires or is terminated, the server deletes the stored session data and releases the session ID and its resources. After this occurs, the server doesn't remember the user or any of the stored data.

A developer can use a session variable to keep track of information as the user navigates around the site, making different requests of the server. For example, as the user shops around on your store's site, session variables can be used to remember the items in a shopping cart. When the user navigates to a new page, that page is requested using a new HTTP connection: the page's code can use a special session ID to add, read, and edit session variables stored on the server.

Sessions can somtimes be more advantageous than regular cookies: Cookies are stored on the user's computer, and many users not wishing to have their privacy violated will configure their browser to refuse cookies but still allow session cookies (although you will still have to add fallback code if the user has chosen to block all cookies).

Additionally, cookies can only store text data and to a maximum of 4096 bytes (that includes the cookie name, expiry date, the cookie's value, etc). Sessions don't have a maximum size, and can contain text, numbers, arrays, or entire objects. However, the server running the scripts might have limits on the maximum amount of memory allocated to a running script; the default value is usually around 128MB so clearly you wouldn't want to store anything in a session that's close to 128MB in size.

Since session data is temporary, developers often use session stores or data stores for storing session data in a more permanent way. For example, when you go to a shopping web site, you might add items to your cart - the contents of your cart are stored in session data so that you can move around the site from page to page without the server forgetting what's in your cart. If you get distracted and step away from the computer, your session might expire before you have a chance to check out. Companies don't want that to happen: they figure if you lose your cart items, you might not have the time or inclination to fill it again. So right before a session expires, the web site might store your cart contents and other session data in a data store so that it's still there if you come back later in the day, or even later in the week.

Sessions are very secure: there are certain kinds of dangers such as session hijacking or session prediction, but good coding practices and good security can prevent these kinds of attacks on your users' session data. When you learn about sessions in your preferred coding language, make sure you find out about the various security measures that you need to implement to make your sessions secure.