In this article, find out how to store and retrieve persistent data with cookies, small files that allow you to do big things. This article explains the basics of cookies, demonstrates reading and writing them in JavaScript, and illustrates their use in a real-world application.
Before you start using cookies, there are a few things you should be aware of:
Cookie technology has been supported correctly since Netscape Navigator 2.0. Internet Explorer users should, however, only use cookie technology on platforms supporting Internet Explorer 4.0 or better, due to errors in the cookie-handling routines of earlier versions.
Since cookies are stored on the user's hard drive, you as the developer have very little control over them. If a user decides to turn off cookie support in his or her browser, your cookies will simply not be saved. Therefore, if data persistence is an important feature of your Web site, have a backup plan (such as server-side cookies or sessions) ready as well.
A single domain cannot set more than twenty cookies. A single cookie cannot exceed 4 KB in size. The maximum number of cookies that may be set is 300.
Now, with the caveats out of the way, let's take a look at the ingredients that make up a cookie.
1. The first element in a cookie is a "name" attribute. Here, the "name" is a string used to identify the cookie (akin to a variable name), followed by the data to be stored in the cookie. This variable-value pair is required; you can't bake a cookie without it. For example,
2. A cookie can also contain an "expires" attribute, which specifies how long the cookie is valid for. For example,
expires
=Fri, 30-Jan-2004 12:00:00 GMT
Setting this element to a date in the past will usually cause the browser to delete the cookie.
3. You can also add a "path" attribute to a cookie -- this states where the cookie may be accessed from on the Web site. Most often, this is set to the server's document root
path
=/
to ensure that the data in the cookie is available to all the scripts on the site.
4. The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional, and might look like this:
domain
=somedomain.com
5. Finally, the "secure" attribute is a Boolean flag indicating whether a secure HTTP connection is required between the client and server to read the data in the cookie. Usually, this is toggled off.
As noted previously, only the first attribute is required; the rest are all optional. If you're using them, remember to separate them with semi-colons, as in the example below: