Page last changed today

Cookies

See section 6G of the book.

This script was originally written by Scott Andrew. Copied and edited by permission.

This article has been translated into French

On this page I give three functions to save, read and erase cookies. Using these functions you can manage cookies on your site.

First an introduction to cookies, and a summary of document.cookie, followed by an example. Then come the three functions and their explanation.

Cookies

Cookies were originally invented by Netscape to give 'memory' to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it, it doesn't remember a thing about it. So if you come to the same web page a second, third, hundredth or millionth time, the server once again considers it the very first time you ever came there.

This can be annoying in a number of ways. The server cannot remember if you identified yourself when you want to access protected pages, it cannot remember your user preferences, it cannot remember anything. As soon as personalization was invented, this became a major problem.

Cookies were invented to solve this problem. There are other ways to solve it, but cookies are easy to maintain and very versatile.

How cookies work

A cookie is nothing but a small text file that's stored in your browser. It contains some data:

  1. A name-value pair containing the actual data
  2. An expiry date after which it is no longer valid
  3. The domain and path of the server it should be sent to

As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the HTTP header. Server side programs can then read out the information and decide that you have the right to view the page you requested or that you want your links to be yellow on a g