11. Cookies

What We Will Cover


Elucidations

Questions from last class?

Homework Questions?

Homework Discussion Questions

  1. Regular expressions are useful, but they can easily get out of hand. What are some warning signs of overly complex regular expressions?
  2. Besides validating forms, what other uses can you think of for regular expressions?
  3. Besides a receipt page, what other uses can you conceive of for passing data from one Web page to another.

11.1: Introduction to Web Cookies

Learner Outcomes

At the end of the lesson the student will be able to:

  • Discuss online shopping cart applications
  • Discuss the history of cookies
  • Describe the limitations placed on a cookie by specification
  • Describe the common uses of cookies

11.1.1: Shopping Carts and Cookies

  • In this lesson we explore the use of HTTP (Web) cookies
  • First we will discuss what a cookie is and what you can and cannot do with them
  • Then we will apply cookies to making a simple client-side shopping cart
  • The shopping cart shows what can be done on the client side and illustrates the uses of cookies
  • Along the way we will make use of the cookie collection in the document object of the HTML DOM

Case Study: Patti's Potpourri

  • To help us learn, the textbook presents a case study on page JVS 377
  • We will work with several linked web pages during this lesson
  • The files, and the names you would save them as, are shown below:
  • In addition, we will use a JavaScript file: patti.js
  • Our job is to develop the front end for an online shopping site
  • We will provide personalized greetings for returning customers
  • In addition, we will accumulate orders and allow customers to review orders before submitting them to the server for processing

About Online Shopping Carts

  • In a supermarket, a shopping cart is a way to collect products that a customer wants to purchase
  • An online shopping cart is a way to simulate a shopping cart on a Web site
  • Typically, an online shopping cart allows customers to select merchandise, review the selection and make changes to their selections
  • The customer usually makes their selection from a catalog of products
  • The shopping cart feeds into a checkout system that completes the order
  • Most shopping carts used on the Web store their data in server-side databases
  • To access the database, the server runs a server-side scripting language such as PHP
    • You can learn how to create these types of applications in CIS-165PH
  • However, it is possible to build a shopping cart system on the client using cookies
  • Client-side shopping carts are harder to administer and maintain
  • Any change to the products requires a recoding of the HTML and JavaScript
  • However, if you do not have access to a server-side database then client-side carts are a viable option for small online stores
  • Building a client-side shopping cart is also a good way to learn about using cookies in JavaScript
  • Also, you can tie a client-side system into a server-side system to get the best of both approaches

11.1.2: About Web Cookies

  • HTTP cookies, or Web cookies, are packets of text sent between the server and the browser
  • The server sends the text to the browser and requests the browser to store the text in a file on the client
  • The next time the browser visits the Web site, it sends the cookie text back to the server
  • Unless the cookie files have been changed in some way, the same text is returned to the server as was originally sent
  • You can see this back and forth interaction in the following diagram

Cookie Flow

  • The cookie data is part of the HTTP headers and thus it does not show up in the HTML part of a Web page
  • You can see the text of a typical cookie in the following image (from Wikipedia)
  • This cookie was set by google.com in response to a page request

    Cookie example

History of Cookies

  • HTTP cookies were invented by Lou Montulli in June 1994
  • At the time, he was working for Netscape Communications
  • The term cookie, or magic cookie, had been used in communication programming for a number of years
  • Lou Montulli decided to use this technique to fix problems with an online shopping cart Netscape was developing
  • Netscape added the ability to save cookies to Version 0.9beta of Netscape
  • Since then, most browsers have supported cookies

Cookie Limitations

  • Cookies have limits imposed by specification
  • The maximum size of a cookie is 4KB
  • A browser can only keep the last 20 cookies sent from a particular server or domain
  • Also, browsers are only required to keep 300 total cookies

Error in the Textbook

  • Unfortunately, the textbook has some conceptual errors on page JVS 481
  • The textbook defines the terms "client-side cookie" and "server-side cookie"
  • Cookies were defined originally in the document Persistent Client State - HTTP Cookies and more recently in RFC 2965
  • Cookies are sent by a Web server and stored on the client by the browser
  • This cookie data is sent back to the client by the browser whenever it revisits the server
  • Thus, it takes both a Web server and client to work with Web cookies
  • JavaScript lets you work directly with cookie data on the client rather than using the server to set cookie data
  • However, the browser still sends the cookie data to the server
  • The server can still change the cookie data and send the changed cookie back to the client
  • Also, the JavaScript to change the cookie usually comes from the server
  • Some people tend to use terms like "client-side cookies" and "server-side cookies" to explain where the cookie data is stored
  • However, this is just confusing and misleading terminology
  • Anything stored on the server is NOT a cookie as you can see by reading the specification
  • Thus, there is no good reason to use terms like "server-side cookies" or "client-side cookies"
  • All HTTP cookies are stored on the client and NOT on the server

More Information

11.1.3: How Cookies are Used

  • Cookies are intended to be a tracking mechanism for Web servers
  • By storing information about the user in a cookie, the server can keep track of the user from request to request
  • Cookies are often used in the following ways

Site Personalization

  • One common use of cookie is site personalization
  • If the user supplies a name or other information, the data can be stored in a cookie
  • One of the Tutorial Case exercises implements a cookie saving user information
  • When the user revisits a page, the page greets them by name

Online Shopping Cart

  • A web application can use cookies to store items a customer wants to buy
  • The Tutorial Case study implements such a shopping cart

Website Tracking

  • By storing a unique identifier in a cookie, web sites can track which pages you visit
  • For instance, a Web server may set a cookie named id as follows:
    id=21347f619da65d945ff091ff3aced6fd
  • Since the browsers sends back any cookie to the server, the server can record the unique identifier in a log file
  • By analyzing the log file, someone can determine which pages you visited, what order you visited them in, and from which page you left the site

11.1.4: Problems with Cookies

  • Cookies are a simple mechanism but do have some potential for misuse
  • Since a cookie is nothing more than text, it cannot do some things
    • Cannot read or write a file
    • Cannot steal a password
    • Cannot format a hard disk
    • Cannot send e-mail
    • Cannot be used to transmit a virus
  • One real risk of cookies is that someone other than the user might read the cookie data
  • For instance, a person might order a product at a public computer
  • As a service to the user, you might be tempted to store a users login and password to make it easier for returning users
  • However, storing login and password data in a cookie is a bad idea
  • Another person can use the public computer and look at the cookie files
  • Generally, you should not store private or sensitive data in a cookie
  • If you must store some ensitive data, you need to encrypt it first with a secure encryption system

Third-Party Cookies

  • Another potential problem with cookies is what is known as a third-party cookie
  • A third-party cookie is a cookie set by a different server than the Web site the user is visiting
  • Third-party Web sites usually provides some content, like images, stored on another server
  • To display the page, the browser downloads this content, possibly receiving cookies
  • When the user visits another page or site using this content, then the browser sends the cookie data to the third-party site
  • As an example, web banners are usually stored on the server of an advertising company
  • This allows the advertising company to track a user across the sites where it has placed a banner
  • Using such techniques, the advertising company can build up a profile for the user
  • This allows the company to select a banner for the user based on their profile
  • Most modern browsers let the user block third-party cookies

More Information

11.1.5: Summary

  • In this section we looked at HTTP (Web) cookies
  • Cookies are text files and they cannot be used to create harmful programs
  • Instead, the purpose of a cookie is to remember information about the clients of a Web server
  • For instance, you can save a users purchase selections in a cookie
  • This can be useful in online shopping applications
  • Other uses of cookies include personalization and advertisement tracking

Check Yourself

  1. What are typical uses of cookies?
  2. What are some differences between a client-side shopping cart and a server-side shopping cart?
  3. What are the risks of storing a users login and password in a cookie?

Activity 11.1

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. Which of the following Netscape versions was the first to support cookies?
    1. 0.9beta
    2. 2.0brelease1
    3. 3.0
    4. 4.5

  2. HTTP is a protocol.
  3. The term cookie is derived from the communication programming term "magic cookie".

    True
    False

  4. A good use of cookies is to store user names and passwords

    True
    False

11.2: Making Cookies

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create new cookies using JavaScript
  • Read cookies using JavaScript
  • Describe the parts of a cookie

11.2.1: Creating a Cookie

  • Now that we know how cookies work, we can look at how to make them
  • Every cookies has five ingredients:
    • name=value: the name that identifies the cookie and the value assigned to the cookie
    • expires=date: the date when the cookie expires and should be deleted
    • domain=domainName: the Web server that may access the cookie
    • path=path: the folders and the files that may access the cookie
    • secure: a marking that the browser can transmit the cookie only if the communication channel is secure (such as HTTPS)
  • Using the DOM property document.cookie, we can create or modify the cookies on the client with JavaScript
  • The syntax for making a cookie is:

    document.cookie = "name=value; expires=expiration; path=path; domain=domainName; secure";

  • Where each ingredient is described above
  • For example:

    document.cookie = "username=ed; expires=Monday, 13-Nov-06 12:34:56 GMT; path=/; domain=http://www.edparrish.com"

  • The name and value are the only required properties
  • The other properties either have default values or are optional
  • We will discuss each of these properties in the following sections

11.2.2: Setting the name and value Attributes

  • Each cookie stores a single piece of information as its value
  • The value is identified with a name when cookie is created
  • For instance, we can create a cookie named "username" with the value "ed" like this:
    document.cookie = "username=ed";
  • Also, we can dynamically generate values for a cookie like this:
    username = document.form1.uname.value;
    document.cookie = "username = " + username;
    
  • Where the Web page contains a form named "form1" with a text field named "uname"
  • You can try setting cookie names and values in the following interactive example
  • Recall that the cookie specification limits browsers to 20 cookies per server or domain
  • Also, each cookie is limited to 4 kilobytes of text per cookie

Interactive Cookie Test

New cookie name:
New cookie value:

Code for Interactive Cookie Testing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script type="text/javascript">
function setCookie() {
    cname = document.cookieform.cookiename.value;
    cvalue  = document.cookieform.cookievalue.value;
    document.cookie = cname + "=" + cvalue;
}
</script>

<form name="cookieform" action="#">
<p>New cookie name: <input name="cookiename">
<br />New cookie value: <input name="cookievalue"></p>
<input type="button" value="Set cookie"
  onclick="setCookie();">
<input type="button" value="Display cookie"
  onclick="alert(document.cookie);">
</form>

11.2.3: Controlling the Expiration Date

  • You can assign a cookie an expiration date
  • The expiration date is the date and time a cookie should be deleted from a browser
  • To assign an expiration date you use the expires attribute with the syntax:
    expires=Day, DD-Mmm-YY HH:MM:SS GMT
  • As shown in the example:

    document.cookie = "username=ed; expires=Monday, 13-Nov-06 12:34:56 GMT; path=/; domain=http://www.edparrish.com"

  • Note that the cookie specification requires use of Greenwich Mean Time (GMT)
  • Also, the separators between the elements of the date must be dashes
  • If you assign an expiration date, you must include the day of the week and the date at a minimum
  • If a cookie is create without an expiration date, it expires when the browser is closed

Another Small Error in the Book

  • On page JVS 488, the textbook states that a cookie set without an expiration date exists only as long as a browser is communicating with a site
  • If actually exists until the user closes the browser, even if the user moves to another site

11.2.4: Specifying the Domain and Path

  • The domain attribute lets you specify the Internet domain name of the host
  • The domain is shown in the following example:

    document.cookie = "username=ed; expires=Monday, 13-Nov-06 12:34:56 GMT; path=/cis132; domain=http://www.edparrish.com"

  • If a cookie does not set a domain, then the domain of the server that sets the cookie is used
  • You can use the path attribute to specify a directory and page in the domain of the URL
  • Thus you can use the path attribute to restrict access to just part of a Web site
  • For instance, to restrict a cookie to the directory cis132, you would set the path attribute as shown in the example above
  • Note that if a cookie does not set a path, then the default setting is the path of the page that generated the cookie

Yet Another Textbook Error

  • On page JVS 489, the textbook states, "By default, a cookie is only available to the page where it originated."
  • This is just plain wrong
  • The default path setting is the path of the page that generated the cookie
  • This certainly does not limit the cookie to a single page
  • Perhaps the textbook meant to say path rather than page?

11.2.5: Using the secure Attribute

  • The final attribute you can set for a cookie is: secure
  • This attribute lets you specify that the cookie is transmitted only over a secure connection
  • Usually a secure connection is made using the HTTPS protocol
  • However, other protocols exists and new ones could be added
  • To set a cookie as a secure cookie, you add the attribute "secure" without a value

11.2.6: Summary

  • In this section we learned how to create and retrieve cookies using JavaScript
  • Also, we explored the attributes we can use to set a cookie
  • To create a value, we assign a valid text string to document.cookie like the following:

    document.cookie = "username=ed; expires=Monday, 13-Nov-06 12:34:56 GMT; path=/cis132; domain=http://www.edparrish.com"

  • To retrieve cookies, we use document.cookie as well:
    alert(document.cookie)

Check Yourself

  1. What is the text used to create a cookie name item with a value of brush and an expiration of Monday, November 13th, 2006 at 12:00 PM Greenwich Mean Time?
  2. What Web pages would be able to access a cookie with a path setting of "/"?
  3. When does a cookie without an expiration date expire?
  4. If a cookie is assigned an expiration date of Monday, November 13th, 2006, what time on this date will it expire?

Activity 11.2

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. When sending a secure cookie, the _______________ protocol is used:
    1. HTTP
    2. SECURE
    3. HTTPS
    4. FTPS

  2. Cookie files can never exceed in size.
  3. All cookie values are assigned to a cookie name.

    True
    False

11.3: Working with Cookie Values

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create a cookie for a first-time Web site visitor
  • Manage the display of a personal greeting to users returning to a site
  • Control the process of creating cookies for use in a shopping cart
  • Manage the deletion of cookies used in a shopping cart application
  • Discuss the process of passing data from one page to another using cookies

11.3.1: Extracting Cookie Values

  • Patti's Web site uses four cookies to remember a visitors first name, last name, username and password
    document.cookie = "fn = " + fn;
    document.cookie = "ln = " + ln;
    document.cookie = "user = " + user;
    document.cookie = "pswd = " + pswd;
    
  • A visitor enters this information on the Account creation page (patti_account.htm)
  • The page is validated using a checkForm() function
  • When it passes the validation, the data is saved in the four cookies
  • Since the site uses multiple cookies, we need a way to find one particular cookie in the list that get returned
  • The textbook defines a findCookie() function to extract a single cookie from a set of cookies
  • A slightly modified version of this function is shown below
  • To use the function, enter code like:
    var user = findCookie("user");

Function findCookie()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function findCookie(cookieName) {
    var cookie = null;
    var findVal = cookieName + "=";
    var dc = document.cookie;
    if (dc.length > 0) {
        var start = dc.indexOf(findVal);
        if (start >= 0) {
            start += findVal.length;
            lastVal = dc.indexOf(";", start);
            if (lastVal == -1) {
                lastVal = dc.length;
            }
            cookie = dc.substring(start, lastVal);
        }
    }
    return cookie;
}

11.3.2: Using Cookies to Personalize Greetings

  • To display a personalized greeting, we need to:
    1. Read they saved first and last name from a cookie
    2. Write the names to a Web page
  • To extract the first and last names, we can use the findCookie() function
    fn = findCookie("fn");
    ln = findCookie("ln");
    
  • With these two value, we can write to a page using document.write():
    document.write("Hello, " + fn + " " + ln + ".");
    
  • You can see this in action by first registering on patti_account.htm
  • After registering, you are redirected to the home page and greeted by name

11.3.3: Implementing a Shopping Cart

  • Now we look at how to implement a shopping cart using cookies
  • The strategy is to show a list of products that a visitor can purchase (patti_trinkets.htm)
  • When the user presses the button next to the item, the information about the item is stored in a cookie
  • To reduce the number of cookies used, we store all the information about a product in one cookie
  • Each product in the cart has four pieces of information:
    • Product number
    • Product name
    • Price per item
    • Item number on page
  • For instance, for a single Ornamental Green Vase the information is:
    • Product number: V212
    • Product name: Ornamental Green Vase
    • Price per item: 8.05
    • Item number on page: 0
  • We separate each piece of information in the cookie value with a comma
  • Using a unique separator character allow us to parse the data when we read the cookie
  • Each button on the page will call a placeOrder() function with the information
  • For instance, the code for the button for the Ornamental Green Vase looks like:

    <input type="button" value="Add to Cart" onclick="placeOrder('V212', 'Ornamental Green Vase', '8.05', 0)" />

  • The placeOrder() function adds the quantity to the information and in turn calls the makeOrderCookie() function shown below
  • Note that each cookie is named myitem followed by a unique number
  • This naming convention makes it easier to retrieve the product cookies using a loop

Function makeOrderCookie()

1
2
3
4
5
6
7
8
9
10
11
12
var expdate = new Date(now.getTime()
    + 14 *24 * 60 * 60 * 1000);

// more code here...

function makeOrderCookie(n, id, prod, pr, q) {
    document.cookie = "myitem" + n + " = " + id + ","
        + prod + "," + pr + "," + q + "; expires = "
        + expdate.toGMTString();
    alert("You have added " + q + " of the " + prod
        + " to your shopping cart.");
}

11.3.4: Displaying Shopping Cart Contents

  • A shopping cart needs some way to show the customer what they are ordering
  • For this, we extract the ordered products from the cookies and display them on a page
  • An array is a good way to hold the data for each cookie (and product)
  • For example, for each cookie we can call the findCookie() function like this:
    var prod = new Array();
    var done = false;
    var itemNum = 0;
    while (!done) {
        product = findCookie("myitem" + itemNum);
        if (product != "") {
            prod[itemNum] = product;
            itemNum++;
        } else {
            done = true;
        }
    }
    
  • Once we have the data loaded into an array, we need a way to display the products
  • Displaying the data is somewhat complicated because the number of products can vary
  • We may need to display no products or four products
  • The usual approach is to display the products in a table
  • To create the rows of the table, we use a loop structure that displays one row for each product
  • The general idea is as follows, though we need usually need to write more than one column of data:
    for (i = 0; i < prod.length; i++) {
        document.write("<tr>");
        document.write("<td>" + prod[i] + "/<td>");
        document.write("/<tr>");
    }
    
  • If we have one product, then the loop runs one time and creates one row
  • If we have four products, the loop repeats four times and creates four rows
  • The showOrder() function shown in the textbook on page JVS 502 will create such a table
  • You can see how to run the showOrder() function on page JVS 503

11.3.5: Deleting a Cookie

  • One other action you need for a shopping cart is to let the customer remove items from the cart
  • To remove items, we just need to delete the cookie for the item
  • To delete a cookie, you simply set its expiration date to some time in the past
  • An easy time to use is the beginning of the UNIX epoch: Thu, 01-Jan-70
  • The book has a function to delete cookies for the shopping cart named delProd()
  • You can see this function below
  • Notice that after the cookie is deleted, the function reloads the page using location.reload()

Function delProd()

1
2
3
4
5
function delProd(prod) {
    document.cookie = "myitem" + prod
        + " = ;expires=Thu, 01-Jan-70 00:00:01 GMT;";
    location.reload();
}

11.3.6: Passing Form Data Using Cookies

  • Previously we looked at sending data from one page to another by appending to the URL
  • Another way to send the data is to use one or more cookies
  • Cookies have some advantages over appending data to the URL:
    • More data can be transmitted (20 cookies x 4KB = 80KB)
    • The user cannot see the transmitted data appended to the URL
  • However, using cookies have disadvantages as well:
    • Some browsers do not support cookies, usually because a user disables them
    • You cannot bookmark a page containing cookie data
  • The textbook has an example of passing form data in section 9.3

Still Another Small Error

  • On page 512, the textbook states that an expired cookie effectively becomes a per session cookie
  • This is not true because an expired cookie is deleted and is no longer returned to the domain
  • However, a per session cookie is still used until the user closes the browser

11.3.7: Summary

  • In this section we looked at some common uses of cookies
  • For instance, we looked at how to use cookies to create a personalized greeting
  • Also, we looked at how to use cookies to create a shopping cart
  • In addition, we looked at how to delete cookies by setting the expiration date to a time in the past

Check Yourself

  1. What is the purpose of storing multiple pieces of information in the value of a single cookie?
  2. How do you retieve a single piece of data when multiple peices are stored in one cookie value?
  3. Why is a table element a good way to display shopping cart data?
  4. How do you delete an existing cookie?

Activity 11.3

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. When creating a personalized greeting, you can use the document.write() to display a cookie value.

    True
    False

  2. When deleting an item from a shopping cart, you should use the method so the page will reload properly.
  3. To delete a cookie, you can set the default expiration date to:
    1. July 4th, 1776 00:00:00 GMT
    2. January 1st, 2038 23:00:00 GMT
    3. January 1st, 1970 00:00:01 GMT
    4. Tomorrow

Wrap Up

Due Next:
A11: Cookies (11/20/06)
Quiz 10 (11/20/06)

Home | WebCT | Announcements | Schedule | Room Policies | Course Info
Help | FAQ's | HowTo's | Links

Last Updated: November 21 2006 @19:10:34