Quick Guide to Using Cookies

What are Cookies?

"Cookies" is a capability of web pages and servers to store information about the user's choices or actions in a non- volatile file on the user's hard disk. For example, as the user moves from page to page and fills out forms the choices could be placed in the special cookies file and used by subsequent pages.  Commerical sites sometimes use this feature to create "shopping baskets" that keep track of what a user is buying.  In another example, users visiting a site could indicate preferences about how they like information displayed.  This information could be stored in the cookie on the user's hard disk and could be used to customize the display each time the user visits.  In computer jargon it is saving "state" information
Cookies were implimented with contemporary browsers - Netscape or Internet Explorer 2.0 or above.  You can actually view your cookie file by looking in the appropriate folder on your hard disk - for example "magiccookie" in Netscape folder in Preferences folder in System folder on the Macintosh.  You can look at it with a word processor if you want - for example setting Word to look at "all files".

Security:

Wait a minute !  Who said the web page could use my hard disk?  The web browser companies swear this is safe.  There is a limit on the size the cookies can take up (approx 4K).  Each site can store only 20 cookies.   Only 200 total cookies can be stored. The only site that can access any particularc cookie is the site that created it.  Cookies can only be simple text - they cannot be executable files that could do damgage Still some critics complain that this information is stored without the user's direct acquiescence or knowledge.  Also, unless a user is web-savvy there is no way to inspect your own cookie.  It is like a secret invisible dossier that goes with you on the web.  Some web enthusiasts are inventing shareware programs to allow users to easily inspect their own cookie. Undoubtedly, some hackers are dreaming up ways to look at other peoples' cookies.
This capability can add sophisticated intelligence and responsiveness to web pages without the capability of server site scripts. It creates interesting possibilities for Web artists. You can expect to see much more use of it in the future.

Limitations:

Cookies may be very tempting to you as a developer.  There are crucial limiations.  Since there is limited space, new cookies can eliminate old cookies;  that is, if the cookie available file space is exceeded by the next cookie, the oldest cookie will be erased.  Also, if the user changes browsers or rearranges folders, the cookie file can be lost. Although you have some control over the date, cookies expire so you can't count on old information still being around.  The cookie may be inaccurate in a shared environment where several people share the same machine.  The size limit on each cookie can thwart some disign.

How does a cookie get set up.

Cookies become part of the headers that the server and browser place at the beginning of Web pages.  There are two ways cookies can be set up:  1. As the user loads a page, sever CGI scripts includes information to access or set up cookies.  2. Javascript can be embedded in the web page to access or store information.  This quick guide will only deal with the javascript method.

What does a cookie contain?

Each cookie contains a label (selected by the developer) followed by the text put into the cookie, followed by the date the cookie was created and the date it is to expire, followed by the domain address of the sites that are allowed to access the cookie. Note that text that includes punctuation marks or spaces will be encoded with hexadecimal codes to reflect those characters. (Check any text on Javascript for details how to encode and decode this kind of text.) Here is part of the cookie on my computer to illustrate. It shows the the path and the expiration date (indicated in seconds) and then label-value pairs.
        FALSE  userwww.sfsu.edu/~infoarts/  FALSE       856031603       numlongc        0

        FALSE   userwww.sfsu.edu/~infoarts/   FALSE  856031603  favcolorc       red

Demonstration of how cookies work

The fields below demonstrate the use of cookies:  The first one is a cookie that only lasts during todays session.  It keeps track of how many times you visit this page and expires at the end of today.  The second is a persistant cookie that lasts longer and cumulates totals over time.  The third displays your previously chosen favorite color. The selection box lets you make a color choice from the selection list and stores it in a cookie when you leave.

How many times visted today Total times ever visited Previous favorite Color
Please pick your favorite color 


Analysis of Script to Use Cookies: Setting up the Cookies

The main parts of the script are 1. Routines to set the value of cookies and 2. Routines to read the value of cookies. Here is the first part of the script that sets default values and also includes the routines that set the values of cookies.
<HTML>
<HEAD>
  <SCRIPT language="Javascript">
 <!C- hide from other browsers

// set read date and set default values for beginning when no cookies exist
var exp = new Date();
exp.setTime(exp.getTime() + 24*60*60*90*1000);
var expDate = exp.toGMTString();
var favcolor;
var name;

// routines to create new cookies ----------

function newCooklong(name,value) {
        document.cookie = name + "=" + value + ";expires=" + expDate;
        return true;
}

function newCookshort(name,value) {
        document.cookie = name + "=" + value + "; "
        return true;
}
 
Cookies take the form of "label1=value1; label2=value2"etc. Creation of a cookie merely requires that the cookie object of the document be assigned a string in the required format. For example document.cookie = "favcolor=red; " would create a cookie called favcolor with the value red. Note that Javascript is very picky; there must be no extra spaces and it must end with a semicolon and a space.

This example script takes the flexible approach of creating two general purpose functions to assign cookie values. Each function requires two parameters - name and value. Thus other parts of the script can call these by substituting the appropriate values. For example, the script could call newCookshort(favcolor,red) to create a new cookie like the one described in the previous paragraph.

You might be wondering why there are two routines. By default cookies expire when a person shuts down the current session of the browser. You can attach a specific expiration date to set the time in the future. In this example scirpt I wanted some of the cookies to expire and some to persist. The routine newCooklong makes cookies that expire 90 days in the future. This is accomplished by adding the phrase "expires = (expiration date)". The routine sets up the variable expDate which uses javascript's date functions. Var exp = new Date() sets the variable exp equal to the current time/date. exp.setTime (exp.getTime() + 90*24*60*60*1000) sets the variable exp equal to the current time plus 90 days worth of 24 hours worth of 60 minutes worth of 60 seconds worth of 1000 milliseconds. To standardize the script converts the time to Greenwich Mean Time (var expDate = exp.toGMTString()).


Getting the Value of a Cookie

The next routines are a generalized function for retrieving the value of a particular cookie. The cookie specification complicates this because the cookies are stored in one running string of characters. You have to use Javascript's string manipulation functions to bite off the particular cookie label/value pair you want.

The function retrieves the entire cookie (document.cookie). It then sets up a loop to start going through all the text looking for the parameter search term you provided it (name). It calculates the length of the search term (templen) and then looks at every substring of that length in the total cookie. It moves the start and end along looking for the term. For example, it could search for the 9 character string "favcolor". If it finds it ot sets a flag called cookieyes = true.

The next part of the function jumps into action once the search label is found. It finds the value of the cookie (the part after the =). Since it knows the start and end of the search label it can then calculate the start of the value (end+1). Cookies end each label/value pair with a ";" so the routine finds the end of the value by finding where the next ";" occurs. It assigns the value it finds to a variable called val.
// routine to get cookie value -----------

function getCookie(name)  {
        var start=0;
        var end=0;
        cookieyes=false;
        var cooktxt= document.cookie;
        var i=0;
        templen = name.length

        while ( i<= cooktxt.length){
                start = i;
                end  = start + templen;
                if (cooktxt.substring(start,end)==name){
                cookieyes = true;
                break;
        } i++

}
        if (cookieyes==true){
        start = end + 1;
        end= document.cookie.indexOf(";",start);
        if (end < start)
                end=document.cookie.length;
        val = document.cookie.substring(start,end);
        }

}
 


Displaying and adjusting the current values of the cookies and initialization

This script is the one called when a document first loads. It retrieves the values of the cookies and displays their values in text fields. Each time you come back to the page in increments the cookie called numshortc, which is keeping track of how many times you enter the page during a session. It also displays the cookie called numlongc which only changes when you first start a session. It must be a persistent cookie that lasts for a long time. Finally it also shows you the favorite color you chose the last time you were on the page - whether during the current session or a previous one.
When the page loads it calls a masterdisplay function that calls specific routines to get and display each of the cookies. Each routine uses the getCookie function described previously. There are a few subtleties to note.
The function must first check if there are any cookies at all. It does this by calling the getCookie function for the cookie called "favcolorc". If the routine can't find a cookie, the variable called cookieyes will be set to false (0). Using an if..then structure it calls the function initcookies(), which creates the basic cookies and assigns starting values to all relevant variables.
After taking care of this it then calls the 3 subfunctions displayshortcook(), displaylongcook(), and displayfavcolor(). Each of these uses the getCookie function to get the current value of each cookie and displays them in the text fields in the form. Since numshortc (the cookie keeping track of todays visits) will not have a value even if there are other cookies, it must be initialized. Again, it calls getCookie and initializes if the value returned indicates the cookieyes value to be false (0). It then increments the value by 1 since it is keeping track of each time the page is loaded.
The displaylongcook() routine is slightly different. It will only increment once for each day's session. It accomplishes this by incrementing only when numshort is = to 1 (<2). That happens only on the first visit to the page.
One more function called getcolor() is necessary to work with the idiosyncracies of the selection field in Javascript. This routine is necessary to get the text of the selected option in the select field called pickcolor. That text is necessary in order to store it in the cookie for favcolorc.
// this calls all the routines to show cookies on loading-------


function masterdisplay()  {
        // see if any cookies exist at all, initialize everything if no
        getCookie( "favcolorc");
        if (cookieyes == 0 ) { initcookies();}
        displayshortcook();
        displaylongcook();
        displayfavcolor();
}

function displayshortcook() {
        // get number of times today
        getCookie("numshortc");
        // initialize value if first time today
        if (cookieyes == 0 ) { val=0;}
        numshort = parseInt(val)+1;
        document.cookieform.shortvisit.value = numshort;
}


function displaylongcook() {
        // get number of times in recent months
        // only increment it for the first time visit today
        // this happens only when numshortc is less than 2 - the first time
        getCookie("numlongc");
        if (numshort<2 ){       
                numlong = parseInt(val)+1;
                document.cookieform.longvisit.value = numlong;
        }
        else
        {numlong = val
        }
}


function displayfavcolor() {
        // get number of times today
        getCookie("favcolorc");
        col = val;
        document.cookieform.favcolor.value = val;
}


// initialize for first time -------------
function initcookies() {
        document.cookie = "numshortc=0; ";
        numshort = 0;
        val = 0;
        document.cookieform.shortvisit.value=0;
        document.cookie = "numlongc=0; " ;      
        document.cookieform.longvisit.value=0;
        numlong = 0;
        document.cookie="favcolorc=none; ";
        favcolor ="red";
        col ="red";
        alert(document.cookie);
}

// - get the color value from selection field
function getcolor() {
        op=document.cookieform.pickcolor.selectedIndex;
        col=document.cookieform.pickcolor.options[op].text;
}

 

Setting the persistant cookies values on shutdown

Finally, when the user quits, the script must set the cookies to reflect the new values of the total of visits to the site and the last favorite color. The masterunLoad() function is called when the page unloads. This function makes calls to the newCooklong() function to set the cookie for the numlongc cookie (keeping track of visits to page beyond one day) and for the favcolorc cookie (keeping track of last color chosen). Since these have their expiration date value set 90 days from the current date, the values are stored in the cookie file on the users hard disk and will be available the next time the user visits the page.
// routine to store the new values for the cookies------

function masterunLoad() {
        newCookshort("numshortc",numshort);
        newCooklong("numlongc",numlong);
        var newfavcolor = col;
        newCooklong("favcolorc",newfavcolor);
}
 

HTML code to activate the javascript routines

.
 The script functions will do nothing unless they are activated. Commands must be embedded in the HTML code of the page to call the functions at the appropriate time. An on load and on unLoad handler are placed in the body header of the page. The onLoad handler calls the masterdisplay() function which gets the cookies, initializes or increments if necessary and displays them when the page is first loaded. The unLoad hander calls the masterunLoad function to reset the cookie values. The selection element of the form contains one on change handler to set the variable col via athe getcolor() javascript function with the current color choice.
<BODY onLoad="masterdisplay()"; onUnload="masterunLoad()"; >
<P>
<FORM ACTION="" METHOD="POST" NAME=cookieform>
  How many times visted today<INPUT TYPE="text" NAME="shortvisit" SIZE="5">
  Total times ever visited<INPUT TYPE="text" NAME="longvisit" SIZE="5">
  Previous favorite Color<INPUT TYPE="text" NAME="favcolor" SIZE="10"> <BR>
  Please pick your favorite color
  <SELECT NAME="pickcolor" onChange="getcolor();"> 
  <OPTION SELECTED >red 
  <OPTION >blue 
  <OPTION >green</SELECT><BR>
  <P>
</FORM>

An example shows how a cookie can be used to determine the next page loaded.  You must select a color in the example above for the demonstration to work.  See the example wilson.cookbranchexpl.html


Summary

Cookies offer amazing opportunities for building intelligence into pages and for abuse. These links provide some more technical details:

- This page created by Stephen Wilson, Professor Conceptual/Information Arts, SFSU (http://userwww.sfsu.edu/~swilson) swilson@sfsu.edu 
- More information about the Conceptual Design program is available at (http://userwww.sfsu.edu/~infoarts)
- It is a resource used in Art511 Art&Telecommunications course (http://userwww.sfsu.edu/~infoarts/Tele/Tele95.index.html)
- A comprehensive guide to Web design is available in the book World Wide Web Design Guide (Hayden Books) by Stephen Wilson
- The url of this page is (http://userwww.sfsu.edu/~infoarts/Tele/wilson.howtoguide.html)