Big Brother Is Watching
In your travels across the Web, I'm sure you've experienced Web sites that seem to know you only too well, displaying your name and email address when you visit them and (in some cases) even remembering the pages you visited the last time you were there. Before you allow your paranoia full rein, though, let me tell you that you probably provided the information yourself to the site in some previous visit, and what you see when you return is merely the results of your own actions, reprocessed for a better visitor experience.
So how do they do it? Well, most of these sites save personal information, such as your name and email address, in files on your hard drive, and read these files every time you re-visit the site. These files are known as "cookies", and they're a simple and easy way to add personalization features to your site. Cookies can also be used to record information about your activities on a particular site; however, they can only be read by the site that created them.
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.
- 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,
- 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.
- 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
to ensure that the data in the cookie is available to all the scripts on the site.
- The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional, and might look like this:
- 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:
document.cookie = "name=Joe; path=/; domain=my.site.com; secure";
Now, let's look at writing some code to create a cookie.
What's In A Name?
Most of this is pretty simple - the prompt() method takes care of popping up a box for user input, and the corresponding value is encoded into the cookie string for storage. Similarly, a Date object is instantiated with the cookie's expiry date, converted to the requisite format using the Date object's toGMTString() method and the resulting value is added to the cookie string as part of the "expires" attribute explained earlier. Once the cookie string is ready, the "document.cookie" property takes care of writing it to a file.
Now, try running the code above in your browser. You should see an input box. Enter your name into the box. The value you entered into the box should now be saved as a cookie to your hard drive. If you're the suspicious type, verify this by looking in your browser's cookies directory - you should see a cookie with contents like this:
username Guru localhost/cookies/ 0 4249743488 29612272 2610381856 29612264
Now, that was pretty simple - but there's more than one way to skin a cat. If you're in a rush and don't have too much time to spend on implementing a custom cookie library, the Web throws up a number of interesting public-domain libraries which are powerful, stable and easy to use.
The best-known of these public-domain cookie libraries is the one created by Bill Dortch in 1996, and used extensively in many sites on account of its rich features and overall stability. Coincidentally, this is also the library I plan to use throughout the rest of this tutorial, so drop by and download a copy before reading any further.
With the Bill Dortch library, setting a cookie is as simple as calling the SetCookie() function with appropriate arguments. The first two of these arguments are the mandatory name and value parameters - these must be set for the cookie to be valid. For persistent cookies, you would also follow these two arguments with an expiry date set to 60 minutes ahead of current time (60 minutes 60 seconds 1000 milliseconds); this will ensure that the cookie is saved to the hard drive and remains valid for 1 hour. For non-persistent (session) cookies, simply omit this expiry date.
Here too, once you've entered your name into the form and hit the "Save!" button, your cookie will be saved to disk in your browser's cookies directory. If you look at the code for the SetCookie() function, you'll see that internally, it does pretty much the same thing you manually did in the example on the previous page.
Running The Numbers
Now, that takes care of writing a cookie. But how about reading back the data you stored in it?
Fortunately, the Bill Dortch library has you covered on that front as well, with its GetCookie() function. To illustrate, consider the following example, which checks for a cookie and retrieves a value from it for display if available:
Here, when the page loads, the GetCookie() function will check to see if a cookie named "username" exists on the client for the specified domain/path combination. If it does, it will be retrieved, the value stored within it will be read, and an alert box will be shown with a welcome message.
Let's look at another example, this one tracking the number of visits that the user has made to the particular Web page:
Here, as before, I use an "if" test to check whether a cookie already exists to track the number of visits. If it does, I use the GetCookie() function to retrieve the value; if it does not, I assume this is the first visit to the page and initialize the counter to 1. The value of the counter is then updated (if necessary) and written back to the cookie in readiness for the next visit.
So that takes care of writing cookies, and then reading the values back. Now, how about a composite example that you can actually use?
In this next example, I'll assume a multi-lingual Web site, where the user has a choice of viewing the content in either French or English. The first time the user visits the site, (s)he is permitted to select one of the two languages. This choice is stored in a cookie, so that on the next visit, the client is automatically redirected to the chosen language without requiring the user to re-select a language.
That was simple enough. When the user visits the page, the code first checks to see if a cookie with the selected language already exists. If it does, the browser is automatically redirected to pages in that language. If no cookie exists, it implies that the user has not selected a language, and so a language choice is displayed. The language selected is then written to a cookie in preparation for the next visit.
Of course, this is just the tip of the iceberg. You can do a lot more with cookies - take a look at the following links for more information:
The Netscape cookie specification, at http://www.netscape.com/newsref/std/cookie_spec.html
Bill Dortch's cookie library, at http://www.webwoman.biz/articles/Cookies/cookie.txt
More sample cookie applications, at http://members.ozemail.com.au/~dcrombie/cookie.html and http://developer.netscape.com/viewsource/archive/goodman_cookies.html
Sample cookie code and demos, at http://www.cookiecentral.com/
Until next time...be good!
Note: Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!This article was first published on 12 Jan 2004.