Using Cookies

Cookies can be put to a number of simple uses. When cookie problems occur, this JavaScript URL is very useful for debugging. It produces a readable report if many cookies are present:

JavaScript:alert(document.cookie.split(';').join('\n'))

Logging in users

Cookies can be used to force browser users to supply usernames and passwords before viewing Web pages. Web servers already have a mechanism for doing this called 'HTTP Authentication', but if you don't like that system, you can use cookies instead. The steps are:

The user name and password might be validated against entries in a private file on the web server, like /etc/passwd on Unix.

This cookie is used to track the user when browsing through pages of the web site.

This is because a user might try and get around the login screen by going directly to the URL of another page. The cookie created cannot be as simple as 'login=true;', because an expert user might see this cookie and just create it with a JavaScript: URL next time he enters the web site, avoiding the login again. The cookie value should be different each time the user logs in (perhaps containing an encrypted time) so that subsequent checks can confirm that the value supplied is recent.

In general, this is not a highly secure login mechanism, but it does prevent unknown users from easily entering your web site. It is less efficient than 'HTTP Authentication'.

If you don't have the opportunity to use CGI programs, you might think that the password can be checked in client-side JavaScript, and then proceed directly to the next page. Yes it can, but it's not secure, because the browser user can always view the JavaScript source and therefore workaround the password-checking code.

Cookies as Bookmarks

There is no way to automate the creation of bookmarks from JavaScript. There is no way to automatically navigate to a specific bookmark. Cookies can be used to workaround these restrictions.

A cookie with an expiry date set way into the future will exist effectively forever. A cookie whose value is a URL can always be used as a bookmark. A simple example:

<!-- redirect.htm -->
<HTML><HEAD>
<SCRIPT SRC="cookie_functions.js"></SCRIPT>
</HEAD><BODY>
<SCRIPT>
function go_there()
{
  if ( GetCookie('favorite') )
  {
    window.location.href = GetCookie('favorite');
  }
}

setTimeout("go_there()",10000);      // 10 seconds delay
</SCRIPT>
Returning you to your favorite location on our website ...
</BODY></HTML>

Provided the 'favorite' cookie has been set at some time in the past, the user can be returned there automatically. This cookie could be set by client-side JavaScript, either automatically or in response to some user input, or it could be set in the browser in the response from a CGI program.

More than one bookmark is possible—use more than one cookie, or if the Netscape 20 cookie limit is close, concatenate all the bookmarks together into one cookie's value and unpack them when needed.

User Preferences

Along with bookmarks, cookies can be used to store a limited range of user preferences. The range is limited because of security hobbles. As for the last section these can be set in a number of ways.

Common preference choices might be:

As the page is downloaded, inline JavaScript can check for special preference cookies and switch to the appropriate page, or adapt the page layout as required.

User Profiling

A web site can use a cookie to track a user's movements around the site. Web servers already have facilities for tracking the number of times each web page gets loaded, but cookies allow extra information to be supplied. Without the user's agreement, nothing can be stored in the cookie that exposes the real identity of the user, but the cookie can be used to show that the anonymous user is the same anonymous user as last time. Also see 'cookie traps' below.

Visit Counter

Possibly the simplest use of a cookie is to store a number in it and increment it each time the user loads a page that lies in the cookies domain and path. This gives the HTML author a simple way of establishing familiarity with the user. An example:

<HTML><BODY><SCRIPT SRC="cookie_functions.js"></SCRIPT>
<SCRIPT>
var visits = GetCookie("counter");
if ( visits && parseInt(visits) )
{
    SetCookie("counter", ++parseInt(visits) + "");
    document.write("Hello old friend on your "+visits+" visit<BR>");
    self.location.href = "top.html";
}
else
{
   var expires = new Date();
   expires.setTime(expires.getTime() + 3E11);   // about 10 years = "forever"
   SetCookie("counter", "1", expires, "");
   document.write("Welcome, Stranger.<BR>");
}

</SCRIPT>
<A HREF="top.html">Enter here</A>
</BODY></HTML>

Shopping Carts

Recall from Chapter 5 that shopping carts work around the limitation that HTML forms are restricted to one document. If you don't want to use a hidden frame and JavaScript variables to store the cart's contents, you can use cookies. There isn't much difference. The main benefit is that cookies are easier to submit to a web server—you don't have to recreate an HTML form, they are submitted directly with every URL request. The main disadvantage is that you have to pack your cart items into and out of the cookie, which can be annoying.

© 1997 by Wrox Press. All rights reserved.