Приглашаем посетить
Грибоедов (griboedov.lit-info.ru)

7.4 Cookies, cookies

Table of Contents

Previous Next

7.4 Cookies, cookies

7.4.1 My first cookie

A cookie is a small piece of information stored on the client machine by a Web page. The Netscape browser stores its cookie in a file called cookies.txt. For IE systems, a whole directory (under the Windows directory) called "Cookies" is dedicated to storing cookie information. Cookies, or cookie information, can be accessed and manipulated using the script feature document.cookie.

The original idea of cookies was to make life easier for surfers to access their favorite Web sites. For example, when you visit a site for the first time, you may be asked to enter your name and perhaps your email address and some other information to identify yourself. The site will then place a cookie containing this information on your system. When you return the next time, the site will request information based on the cookie on your machine to determine who you are and perhaps whether you have authorization to access the site.

Cookies are an important, and yet controversial, issue on the Internet. A number of online shopping facilities use cookies to store the shopping items (i.e., the shopping trolley). Since cookie messages are unprotected and transparent to users, they create serious security issues and affect each Web user.

Let's now take a look at how a Web site (e.g., www.pwt-ex.com) can set a cookie in your local machine. Consider the example ex07-13.htm:



Example: ex07-13.htm - Set My First Cookie

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Set My First Cookie - ex0713.htm </title></head>
 6: <body style="background-color:#000088;font-family:arial;font-size:16pt;
 7:       text-align:center;color:#ffff00">
 8: <h2 style="font-size:22pt;color:#00ffff">Welcom To WWW.PWT-EX.COM</h2>
 9: <img src="line1.gif" width="450" height="6" /><br /><br />
10: <script>
11:  var expDate = new Date ()
12:  expDate.setTime(expDate.getTime() + (1000 * 60 * 60 * 24))
13:  document.cookie="Username=JohnSmith; expires="+expDate.toGMTString()
14:  document.cookie="Email=JohnSmith@isp.com; expires="+expDate.toGMTString()
15: </script><br />
16: <div> Practical Web Technologies</div>
17: <div>We Have Put Cookies In Your Machine</div>
18: </body>
19: </html>

If you visit this page from www.pwt-ex.com, the site will put two cookies (lines 13 and 14) in your machine, one to store the name of the user and the other to store the email address.

Basically, every cookie consists of three parts: cookie name, cookie value, and an expiry date. The cookie name and value can be any character string representing the information that you want to store. The expiry date will determine the life of the cookie. If the date is before the current time, the cookie is deleted immediately. If no expiry date is set, the cookie will be deleted soon after your Web session. Usually, this date can be set by the following procedure:

  • Get the current time.

  • Add a counting number in terms of a thousandth of a second.

A typical example is demonstrated in lines 1112. The counting number 1000*60*60*24 in line 12 represents one day. If you want the cookie to last for a year, you can use the counting number 1000*60*60*24*365.

The general format to set a cookie in a client machine is



document.cookie="cookieName=cookieValue; expires=expirationDate"

The three variables cookieName, cookieValue, and expirationDate are user defined. They form the basic components of a cookie. All cookie transactions between the browser and server are normally transparent to users. We deliberately put some output messages (lines 1617) in our example to notify us (see Fig. 7.21).

Figure 7.21. ex07-13.htm

graphics/07fig23.jpg


The interesting thing is that when you visit the site www.pwt-ex.com again, your browser will search for cookies from www.pwt-ex.com and return them as a string in document.cookie. Example ex07-14.htm shows how to design a page to read cookies.



Example: ex07-14.htm - Display My Cookie

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Display My Cookie - ex0714.htm </title></head>
 6: <body style="background-color:#000088;font-family:arial;font-size:16pt;
 7:       text-align:center;color:#ffff00">
 8: <h2 style="font-size:22pt;color:#00ffff">Welcom To WWW.PWT-EX.COM</h2>
 9: <img src="line1.gif" width="450" height="6" /><br /><br />
10: <script>
11:   if (document.cookie == "")
12:   {
13:     document.write("There Are No Cookies Here<br />")
14:     document.write("You Are New To Us. Welcome!")
15:   } else {
16:     document.write("You Have Visited Us Before <br />")
17:     document.write("Cookie Information: <br />")
18:     document.write(document.cookie)
19:   }
20: </script><br />
21: </body>
22: </html>

The main operation of this example is a conditional statement on document.cookie (lines 1119). You know that you have a new visitor if the string is empty. If the string is not empty, you can output the cookie information as illustrated in Fig. 7.22.

Figure 7.22. ex07-14.htm

graphics/07fig24.jpg


The next section shows how to construct a Web page with counting and last visit capabilities.

7.4.2 Counting and remembering last visit with cookies

Let's see how you can develop a Web page with counting and last visit functionalities. We know from the structure of cookies that the most basic cookie controls are to set and get cookie values. You first need to develop two script functions setCookie()and getCookie(). These functions will also be used later in section 7.4.4 to build a cookie library. This page remembers every visit by someone with a last visit date and time stamp. The program code is shown in ex07-15.htm.



Example: ex07-15.htm - Counting And Last Visit Date And Time

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Counting and Last Visit - ex0715.htm </title></head>
 6: <body style="background-color:#000088;font-family:arial;font-size:16pt;
 7:       text-align:center;color:#ffff00">
 8: <h2 style="font-size:22pt;color:#00ffff">Welcom To WWW.PWT-EX.COM</h2>
 9: <img src="line1.gif" width="450" height="6" /><br /><br />
10:
11: <script>
12:   function setCookie(cookieName, cookieValue, expDate)
13:   {
14:     var cookieSt = cookieName + "=" + escape(cookieValue) +
15:       ((expDate) ? "; expires=" + expDate.toGMTString() : "")
16:     document.cookie = cookieSt
17:   }
18:
19:   function getCookie(cookieName)
20:   {
21:    var cookieItem = document.cookie.split("; ")
22:    for (i=0; i< cookieItem.length; i++) {
23:     if (cookieName == cookieItem[i].split("=")[0])
24:      return unescape(cookieItem[i].split("=")[1])
25:     }
26:     return null
27:    }
28:
29:    cTime = new Date
30:    expDate = new Date
31:    expDate.setTime(expDate.getTime() + (1000 * 60 * 60 * 24*365))
32:
33:    pCount = eval(getCookie("pageCount"))
34:    pCount++
35:    lVisit = getCookie("lastVisit")
36:    if (lVisit == null) lVisit = ""
37:
38:    setCookie("pageCount",pCount,expDate)
39:    setCookie("lastVisit",cTime,expDate)
40:
41:    document.write("You Have Visited Us "+pCount+" times.<br />")
42:    if (lVisit != "")
43:      document.write("Your Last Visit Was : <br />" + lVisit)
44:
45: </script>
46: </body>
47: </html>

The setCookie() function in lines 1217 takes the cookieName, cookieValue, and expDate (expiry date) as arguments and sets the cookie accordingly. The command escape(cookieValue) at the end of line 14 is used to turn the cookieValue into an escape format so that spaces and other special characters can be handled correctly.

The getCookie()function in lines 1927 takes one argument, namely, cookieName. This function returns the cookieValue associated with the argument. First, this function splits the entire cookie string from document.cookie into an array of cookieItem (see line 21). Then string comparison takes place to identify the cookieName (lines 2223). If a match is found, the cookieValue will be returned as a unescape string (line 24).

The rest of the program is simple. This page will plant two cookies (the pageCount and lastVisit cookies) on the client machines. The value of the pageCount is a number to record the number of visits. The value of lastVisit is a string representing the time of last visit. We first use the getCookie() function to get the value of pageCount (line 33). This value is incremented by 1 (line 34) and then the value is put back as a cookie (line 38). You obtain the lastVisit information in line 35. Update this value with the current time and put it back as a cookie (line 39). Finally, you output the stored values pCount and lVisit to the screen (lines 4143). In this way, both the pageCount and lastVisit cookies will be updated after each visit. Figure 7.23 shows a screen shot of ex07-15.htm.

Figure 7.23. ex07-15.htm

graphics/07fig25.jpg


7.4.3 Deleting some or all of your cookies

Since the lives of cookies depend on their expiry dates, one natural way to delete them is to reset this value. For example, the line of code



eDate.setTime(eDate.getTime() - (1000 * 60 * 60 * 24))

will get yesterday's date. If you set this date on a cookie, the cookie will be deleted immediately. For example, one can use the following code ex07-16.htm to delete the pageCount cookie to restart a page count.



Example: ex07-16.htm - Restart Page Count

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Re-start Page Count - ex0716.htm </title></head>
 6: <body>
 7: <script>
 8:   cTime = new Date
 9:   expDate = new Date
10:   expDate.setTime(expDate.getTime() - (1000 * 60 * 60 * 24))
11:   document.cookie="pageCount=0; expires="+expDate
12: </script>
13: </body>
14: </html>

Figure 7.24 shows the result when you run ex07-16.htm to delete the pageCount cookie and then rerun the previous example ex07-15.htm to show the page count.

Figure 7.24. After restarting the counter in ex07-16.htm

graphics/07fig26.jpg


The following example shows how to delete all your cookies. The page begins by displaying all your cookies. If you click the Delete button, all your cookies will be deleted.



Example: ex07-17.htm - Delete All Cookies

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Delete All Cookies - ex0717.htm </title></head>
 6: <body style="background-color:#000088;font-family:arial;font-size:14pt;
 7:       text-align:left;color:#ffff00">
 8: <h2 style="font-size:22pt;color:#00ffff">Delete All Your Cookies</h2>
 9: <img src="line1.gif" width="450" height="6" /><br /><br />
10:
11: <script>
12:  function showCookies()
13:  {
14:   if (document.cookie !="")
15:   {
16:    cookieItem = document.cookie.split("; ")
17:    document.write("You Have "+cookieItem.length+" cookies<br /><br />")
18:    for (i=0; i< cookieItem.length; i++)
19:    {
20:     document.write("Cookie Name = "+cookieItem[i].split("=")[0]+"<br />")
21:     document.write("Cookie Value = "+
22:       unescape(cookieItem[i].split("=")[1])+"<br />")
23:    }
24:   } else
25:   document.write("<br />You Have No Cookies! <br />")
26:  }
27:
28:  function delAllCookies()
29:  {
30:   if (document.cookie !="")
31:   {
32:    eDate = new Date
33:    eDate.setTime(eDate.getTime() - (1000 * 60 * 60 * 24))
34:    cookieItem = document.cookie.split("; ")
35:    for (i=0; i< cookieItem.length; i++)
36:    {
37:      document.cookie=cookieItem[i].split("=")[0]+
38:       "=; expires="+eDate.toGMTString()
39:    }
40:   }
41:  }
42: showCookies()
43: </script><br />
44: <input type="button" value="Delete Cookies"
45:    onclick="delAllCookies();location.reload()" />
46: </body>
47: </html>

This example consists of two script functions, showCookies() (see lines 1226) and delAllCookies() (see lines 2841). First, we activate the showCookies() function (line 42) to display all cookies. A button with caption "Delete Cookies" is then created in lines 4445. If this button is pressed, the function delAllCookies() will delete all cookies. The function location.reload() in line 45 is used to reload the page. Figure 7.25 shows all your cookies, and Fig. 7.26 demonstrates the deletion process.

Figure 7.25. ex07-17.htm

graphics/07fig27.jpg


Figure 7.26. After the deletion

graphics/07fig28.jpg


7.4.4 Practical use of cookie functions (cookie library)

In this section, we want to group and modify some of the cookie functions to build a small cookie library. The basic functions in the library are:

setCookie()

Set cookie information.

getCookie()

Get cookie value by cookie name.

delCookie()

Delete cookie by name.

delAllCookies()

Delete all cookies.


We will put these functions into a single external script file called cookie.js and use this library and its functions in later examples.



Example: cookie.js - The ECMAScript File For Cookies

 1: function setCookie(cookieName, cookieValue, expDate)
 2: {
 3:   if ((cookieName=="")||(cookieValue==""))
 4:   {
 5:     document.write("Error..setCookie requires Name and Value")
 6:   } else {
 7:     var cookieSt = cookieName + "=" + escape(cookieValue) +
 8:       ((expDate) ? "; expires=" + expDate.toGMTString() : "")
 9:     document.cookie = cookieSt
10:   }
11: }
12:
13: function getCookie(cookieName)
14: {
15:  if (document.cookie !=""){
16:   var cookieItem = document.cookie.split("; ")
17:   for (i=0; i< cookieItem.length; i++) {
18:    if (cookieName == cookieItem[i].split("=")[0])
19:      return unescape(cookieItem[i].split("=")[1])
20:   }
21:  }else
22:    return null
23: }
24:
25: function delCookie(cookieName)
26: {
27:  if (document.cookie != "")
28:  {
29:   eDate = new Date
30:   eDate.setTime(eDate.getTime() - (1000 * 60 * 60 * 24))
31:   document.cookie = cookieName + "=;expires="+eDate.toGMTString()
32:  }
33: }
34:
35: function delAllCookies01()
36: {
37:  if (document.cookie !="")
38:  {
39:   eDate = new Date
40:   eDate.setTime(eDate.getTime() - (1000 * 60 * 60 * 24))
41:   cookieItem = document.cookie.split("; ")
42:   for (i=0; i< cookieItem.length; i++){
43:    document.cookie=cookieItem[i].split("=")[0]+
44:      "=;expires="+eDate.toGMTString()
45:   }
46:  }
47: }
48:
49: function delAllCookies(confirmV)
50: {
51:   if (confirmV !="Confirm")
52:   {
53:     delAllCookies01()
54:   } else {
55:     if (confirm("Delete Them all?"))
56:     delAllCookies01()
57:   }
58: }

To build a general purpose library, you need to modify some of the previous functions slightly. The setCookie() (see lines 111) and getCookie() (see lines 1323) functions are very similar to those in example ex07-15.htm. We have added some codes into the functions to protect our program. The delCookie() function in lines 2533 will now take an argument, the name of the cookie, and delete that cookie accordingly. The function delAllCookies()in lines 4958 calls the function delAllCookies01() to delete all cookies quietly. If you execute this command with a Confirm string, i.e., delAllCookies("Confirm"), a confirm box will be displayed before any deletion is executed. You will see how to use this library to solve some simple practical tasks in the next section.

Before you write any code to use the library, you will find that a testing function showCookieTable() at the end of the library to show all available cookies and values is useful.



Listing: Continuation Of The ECMAScript File cookie.js

59: function showCookieTable()
60: {
61:  var localMsg=""
62:  var cookieTable=""
63:  if (document.cookie !=""){
64:   var cookieItem = document.cookie.split("; ")
65:   for (i=0; i< cookieItem.length; i++)
66:   {
67:     localMsg=localMsg+"<tr><td width='140'>"+
68:        cookieItem[i].split("=")[0]+"</td>"+
69:        "<td width='300'>"+
70:        unescape(cookieItem[i].split("=")[1])+"</td></tr>"
71:   }
72:   cookieTable="<table>"+localMsg+"</table>"
73:   document.write(cookieTable)
74:  }else
75:    document.write("There Is No Cookie Here")
76: }

This function collects all cookies and formats them into an XHTML table string. A function like this may not be absolutely necessary but, in many cases, is convenient for the purpose of testing and further development.

To use the library, you need to include the line of code



<script src="cookie.js"></script>

before any function call is made. With the use of this libary, it is easy to set and display cookies. We will show you how to use them to develop an online shopping cart application later. First, let's write a Web page to test the cookie functions.

7.4.5 Manipulating cookies with library functions

As a mean of testing the library functions, we create some general information about users:

UserName

To store the user name

Emai

Email address

ShoppingId

Shopping identity for online shopping

Address

Home address

State

State

Country

Country

Tel

Telephone number


This information is stored as cookie names on local machines. To manipulate cookies, six buttons are created:

Set Some Cookies

Fill cookie information

Del Information

Delete information with prompt box

Del Cookies Quietly

Delete all information quietly

Del Cookies (Confirm)

Delete all information with confirm box

Show Cookies

Show cookie information

Reset Email

Reset email address with prompt box


The first button fills the cookies with user information. This is just a test example, but in real applications you should display a form for the visitor to fill in. Forms and user input will be discussed in later chapters when server technologies are introduced. If you click the first and the Show Cookies buttons, you should see the screen as shown in Fig. 7.27. The Del Information button displays a prompt box to ask you to enter the information you want to delete. If you enter "ShoppingId," the ShoppingId cookie will be deleted (see Fig. 7.28). You may need to press the Show Cookies button to see the result.

Figure 7.27. ex07-18.htm

graphics/07fig29.jpg


Figure 7.28. Delete the "ShoppingId"

graphics/07fig30.jpg


If you press the Del Cookies (Confirm) button and select OK in the confirm box, all your cookies will be deleted (see Fig. 7.29). Finally, if you press the Reset Email button, the current email address will appear in a prompt box for you to modify. You can change your email address as shown in Fig. 7.30 and then display the result by pressing the Show Cookies button.

Figure 7.29. Delete all cookies

graphics/07fig31.jpg


Figure 7.30. Prompt for email

graphics/07fig32.gif


With the cookie library cookie.js, this page can be easily developed. The coding is given in ex07-18.htm.



Example: ex07-18.htm - A Page To Test The Cookie Library

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title> Test The Cookie Library - ex0718.htm </title></head>
 6:
 7: <style>
 8:   .tx01{background-color:#000088;font-family:arial;
 9:      font-size:14pt;color:#ffff00;text-align:center}
10:   .tx02{font-size:22pt;color:#00ffff}
11:   .butStyle{background-color:#aaffaa;font-family:arial;font-weight:bold;
12:      font-size:12pt;color:#008800;width:180px;height:30px}
13: </style>
14:
15: <body class="tx01" align="center">
16: <span class="tx02">Welcome To WWW.PWT-EX.COM</span><br />
17: <img src="line1.gif" width="450" height="6" /><br /><br />
18:
19: <script src="cookie.js"></script>
20: <script>
21:  function setSomeCookies()
22:  {
23:   delAllCookies()
24:   expDate = new Date
25:   expDate.setTime(expDate.getTime() + (1000 * 60 * 60 * 24*365))
26:   setCookie("UserName","John Smith Junior",expDate)
27:   setCookie("Email","JohnSmith@isp.com",expDate)
28:   setCookie("ShoppingId","0123456789",expDate)
29:   setCookie("Address","188 Sunny Road, Los Angeles",expDate)
30:   setCookie("State","California",expDate)
31:   setCookie("Country","USA",expDate)
32:   setCookie("Tel","11223344",expDate)
33:  }
34:
35:  function delInfo()
36:  {
37:   userInfo = prompt("Enter The Information To Delete")
38:   if (userInfo !="")
39:   delCookie(userInfo)
40:  }
41:
42:  function resetEmail()
43:  {
44:   expDate = new Date
45:   expDate.setTime(expDate.getTime() + (1000 * 60 * 60 * 24*365))
46:   userEmail = prompt("Enter Your Email",getCookie('Email'))
47:   if (userEmail !="")
48:   setCookie("Email",userEmail,expDate)
49:  }
50:
51:    window.resizeTo(620,550)
52:    showCookieTable()
53: </script><br />
54:
55: <input type="button" value="Set Some Cookies"
56:    class="butStyle" onclick="setSomeCookies()" />
57: <input type="button" value="Del Information"
58:    class="butStyle" onclick="delInfo()" /><br />
59:
60: <input type="button" value="Del Cookies Quietly"
61:    class="butStyle" onclick="delAllCookies()" />
62: <input type="button" value="Del Cookies (Confirm)"
63:    class="butStyle" onclick="delAllCookies('Confirm')" /><br />
64:
65: <input type="button" value="Show Cookies"
66:    class="butStyle" onclick="location.href='ex07-18.htm'" />
67: <input type="button" value="Reset Email"
68:    class="butStyle" onclick="resetEmail()" />
69: </body>
70: </html>

The six buttons created in lines 5568 all have XHTML scripting features. Each button is associated with one script function. The first button function setSomeCookies() defined in lines 2133 is simply a series of function calls to setCookie() functions. This is necessary to make sure that we have something to play with. The second button function delInfo() as defined in lines 3540 will first display a prompt box (line 37) and then delete the information you want to delete. The Del Cookies Quietly and Del Cookies (Confirm) buttons are used to call the library directly. Since we have used the library function showCookieTable() in line 52 before any real actions, the Show Cookies button defined in lines 6566 is just a reload of this page. Again the Reset Email button and hence the function, lines 4249, is designed to use the prompt box to display and obtain the email address.

This example shows that implementation of the library will make a complex program more simple, efficient, and readable. This technique plays an important role in real programming practice. Let's now consider a practical example.

    Table of Contents

    Previous Next