Cookies

Since HTTP is a stateless protocol, preserving state ("persistent data") is one of the challenges faced by web developers. Techniques:


A cookie is:

Cookie properties and restrictions:

A Typical Cookie

Here's a line from cookies.txt:

www.keller.com FALSE /javascript/chap14 FALSE 909700248 FavWine chablis

The fields are tab-delimited. They include:

Javascript programmers don't create these lines explicitly.

Storing a Cookie

Here's an example. It stores a cookie value that expires in one day. Here's the source code. Observe:

Retrieving a Cookie

document.cookie is just a string.


  function getCookie(Name) {
      var search = Name + "="
      if (document.cookie.length > 0) { 
          offset = document.cookie.indexOf(search) 
          if (offset != -1) {
              offset += search.length 
              end = document.cookie.indexOf(";", offset) 
              if (end == -1) 
                  end = document.cookie.length
              return unescape(document.cookie.substring(offset, end))
          } 
      }
      return ""
  }

Lab

Your tasks:

  1. Find your cookies.txt file.
  2. Microsoft Internet Explorer doesn't store cookies in a file named cookies.txt. Where does it store them?
  3. Write a web page containing Javascript that retrieves the cookie (named FavoriteWine) stored by the example program.

Solution

Don't peek unless you're stuck!