Graham Waldon

May 1, 2001

CS377c Assignment 3

Information Cookies

Motivation: It is often useful for a web page to be able to retain information about a user. This allows the creator of the site to keep track of such things as user preferences, or the contents of a shopping cart, which can enhance the usefulness of the site.

Problem: HTML alone is not designed for keeping track of data. It is simply a markup language, instructing the browser in how to display some, usually fixed, content. If the pages are dynamically generated by a script, then forms with hidden fields could be used to keep track of information, but this can cause other problems. The links in the page must pass the data along, either by submitting a form or by including it in the URL. Otherwise, it may be lost. For instance, if the user places items in a shopping cart on a web page, then uses his or her browser’s Back button, they may find that some of their items have disappeared.

Solution: These problems can be avoided, however, by the use of cookies. Cookies allow you to store information in simple name/value text pairs on the user’s computer, with their consent, of course. For instance, in the shopping cart example, you might store cookies such as numItems=3. This data can be updated at any time and is automatically included with each request for a new web page from the original server. The data can also be as persistent as you like, by giving it an expiration date. There is no problem now with losing changes or forgetting to pass information along.

Therefore: When creating web pages and applications that need to keep track of data, use cookies to store the information on the user’s browser.

Figure 1: Sample JavaScript for manipulating cookies. (Adapted from Core Web Programming, by Marty Hall.)

function storeCookies() {

var expires = "; expires=Friday, 31-Dec-01 23:59:59 GMT";

var first = document.myForm.firstField.value;

var last = document.myForm.lastField.value;

document.cookie = "first=" + first + expires;

document.cookie = "last=" + last + expires;

}

function cookieVal(cookieName) {

var startLoc = document.cookie.indexOf(cookieName);

if(startLoc == -1)

return(""); // no such cookies

var sepLoc = document.cookie.indexOf("=", startLoc);

var endLoc = document.cookie.indexOf(";", startLoc);

if (endLoc == -1) // Last one has no ";"

endLoc document.cookie.length;

return(document.cookie.substring(sepLoc+1, endLoc));

}