blank.gif
webreview.com - Cross-Training for Web Teams
Search for: 
Jump to:
blank.gif
blank.gif

 
 

A Songline PACE Production



Serving Cookies to Your Visitors

by Brent Michalski
Aug. 7, 1998
 
 

Ever been to a site that told you how many times you personally had visited? How the heck did they do that? Chances are very good the site used cookies. Cookies are a simple way you can make your Web pages remember information about your visitors.

This week we cover what cookies are and how to use them. By utilizing the power of the CGI.pm Perl module, you too can create cookies easily.

Cookie Info 

View the demo


View the demo.

When we talk about cookies in the context of the Web, we're talking about small pieces of information stored on a user's computer so that you, the Web author, can retrieve them at a later time.

How did they get the name cookies? Cookie functionality originated in the Netscape browsers but I don't think anybody except the people in the room when they were naming them knows why they are called cookies. I have searched for this answer but nobody seems to be talking.

Are cookies secure? Cookies are secure. Given that cookies are only written to a single text file that the programmer has NO control over and that they must follow other rules set by the browser, cookies are secure.

Cookies cannot gather any information from your computer other than what is normally sent when you visit a Web site. Beyond that, cookies only contain information that you provide them. Here are the rules for Netscape Navigator as of version 3.0. The rules may change a little with the different browsers so use these as a guide, they are not etched in stone.

  • A maximum of 300 cookies can be stored on the user's system.
  • No cookie can be larger than 4 kilobytes.
  • No server or domain can place more than 20 cookies on a user's system. (You can't hog all 300 cookies.)
If you go beyond the maximum, the browser will just discard old cookies to make room for the new ones.

Cookie Specifics 

Cookies can contain the following information:
  • Name (Required) You must name your cookie so that you can retrieve the information later. 
  • Expires (Optional) This tells the browser when to get rid of this cookie. It's optional -- if you omit it, the browser remembers the information until you close your browser. The next time you start your browser, the cookie will be gone. 
  • Domain (Optional) Normally left blank because the default setting is the host name of the server that set the cookie, which is what you want. 
    • Domain, when set manually, must have at least 2 dots in it. (You cannot set it to .com, but you could set it to www.webreview.com (notice the 2 dots)
    • Only hosts within the specified domain can set a cookie for a domain. (You cannot set a domain of www.microsoft.com from www.netscape.com) 
  • Path (Optional) Sets the subset of URLs in a domain that the cookies are valid for. If it is not specified, then the current path is used. 
  • Secure (Optional) If the cookie is set to secure, then the cookie will be transmitted only when it is requested from a secure server. The default is not secure. 

Cookie Uses 

Cookies are very useful. They can be used to do simple things like count the number of visits by a user to a Web site, or more complex things like automatically passing user name and password information to a site when a user arrives.

Like many user name and password transactions on the Web, sending a user name and password via a cookie is not a secure transaction unless you are using a secure server and you set the cookie to be secure. Also remember that the user name and password will be stored on the user's computer in an unencrypted text file.

Cookies are also widely used in electronic commerce, or shopping cart, programs. You've probably used these, where a you can "shop" for the items you want and "add" them to your "cart."

The cart component of the application usually sets a cookie on the user's machine so that it remembers what items the user wanted. By using cookies, users could leave the site and when they come back, their items are still in their "cart," even if they haven't visited for several days -- or even years -- depending on the expiration date of the cookie.

On To Our Program 

Our example program this week stores the user's name and how many times they have visited the site. It retains this information in a cookie for 3 days. If you come back after 3 days, it will have forgotten all about you and ask you to enter your information again.

I have numbered the lines of code. As always, the line numbers are not part of the program. If you want to see the program without the line numbers, click here. The line numbers simply make it easier for me to talk about the program.

1: #!/usr/bin/perl
2: use CGI qw/:standard :netscape/;
3: $name=param('name');
4: $name   = cookie('name') if($name eq "");
5: $visits = cookie('visits');
6: if ($name eq ""){
7:   &Register;
8:   exit;
9: } else {
10:   &Welcome;
11:   exit;
12: }
13: sub Register {
14:   print header();
15:   print start_html('Cookie Example'),
16:    center(
17:     font({-SIZE=>6,-FACE=>'ARIAL'},'Cookie Example'),
18:     hr({-WIDTH=>'85%'}),
19:     start_form,
20:      font({-SIZE=>2,-FACE=>'ARIAL'},
21:       b('Please enter your name: ')
22:      ),  # Close font tag.
23:      input({-TYPE=>'text',-NAME=>'name'}),
24:      p(),
25:      submit(),
26:     ), # Close center tag.
27:     p(),
28:     hr({-WIDTH=>'85%'}),
29:    end_form,
30:   end_html;
31: }
32: sub Welcome{
33:   $visits = 0 if($visits eq "");
34:   $visits++;
35:   $cookie_name = cookie(-NAME=>'name',-VALUE=>"$name",
-EXPIRES=>'+3d');
36:   $cookie_visits = cookie(
-NAME=>'visits',-VALUE=>"$visits",-EXPIRES=>'+3d');
37:   print header(-cookie=>[$cookie_name,$cookie_visits]);
38:   print start_html('Cookie Example'),
39:    center(
40:     font({-SIZE=>6,-FACE=>'ARIAL'},'Cookie Example'),
41:     hr({-WIDTH=>'85%'}),
42:     font({-SIZE=>3,-FACE=>'ARIAL'},
43:      b("Welcome back $name!<BR>You have been here
$visits time(s)."),
44:      p("Had this been a real-world Web site
45:         using cookies, it might have automatically logged 
46:         you in, or showed items that you had in a 
47:         shopping cart."),
48:      p("Notice that it remembered who you are and how many 
49:         times you have been here."),
50:      hr({-WIDTH=>'85%'}),
51:     )
52:    ),
53:   end_html;
54: }

Line-by-line Explanation 

Line 1: Tells the program where to find Perl on the Web server. This line will vary depending on where Perl is installed on your server, so you need to make any necessary changes. On a UNIX server, this line is required. If you are running this program on an NT server, this line is not required but won't hurt anything if included. 

Line 2: Loads the CGI.pm module into the program. The arguments in the qw/:standard :netscape/ bring in more subroutines for us to use in our program. These subroutines are all part of the CGI.pm module.

Line 3: Reads the variable called name from the form on the calling Web page and stores it in the variable called $name.

Line 4: Sets the variable $name to the value stored in the cookie called name if the value of $name is empty. We do this because if $name was empty, then either the user didn't enter the information, or they bypassed the FORM part of this program. The subroutine cookie is part of the CGI module.

Line 5: Reads the cookie called visits and stores the results in a variable called $visits

Note: In both lines 4 and 5, if there is not a cookie already set, the variable will simply be filled with nothing.

Line 6: This is the if statement which determines what the program is to do. It checks to see if $name is empty. If $name is empty at this point, then there wasn't a cookie previously set and the user didn't submit any information -- so we call the Register subroutine in Line 7.

Line 8: Exit the program, we are done if we took this path.

Line 9: The else statement says if $name was not empty, then we go here. Note that if it was not empty, then the value was either sent from the form, or passed in as a cookie.

Line 10: Calls the Welcome subroutine which welcomes the user back.

Line 11: Exits the program. We are actually done at this point. We do all of our work in the subroutines below.

Line 12: Closes our if..else statement.

Line 13: Begins our Register subroutine.

Line 14: Prints the standard HTML header. This is called to a subroutine contained in the CGI module that does a:
print "Content-type: text/html\n\n";

Line 15: Starts our HTML and puts "Cookie Example" in the <TITLE> tag. Again these are subroutines contained in the CGI module to generate our HTML. These subroutines allow us to generate the HTML easily. Notice that I do not use a semi-colon until the end of what I want printed. This single print statement spans lines 15-30 and shows the power of CGI.pm.

Line 16: Calls the center subroutine from the CGI module. This puts the <CENTER> tag around whatever is contained in it.

Line 17: Sets the font to ARIAL with a size of 6, and then prints "Cookie Example" for our page title.

Line 18: Creates a horizonal rule tag like this: <HR WIDTH=85%>.

Line 19: Creates the HTML required to begin an HTML form. Since I didn't provide it with any parameters, CGI.pm creates a form which will call itself. 

Line 20: Another font tag, this time our font size is smaller and we don't close it right away since we want this text to span multiple lines.

Line 21: Prints the text to the page in bold format. We are still inside the FONT tag from line 20 so it will be ARIAL with a size of 2.

Line 22: Closes the font tag from line 20.

Line 23: Creates an INPUT box so that we can get the user's name. We call it name.

Line 24: Generates a <P> tag.

Line 25: Creates the form's submit button.

Line 26: Closes our center tag from line 16.

Line 27: Generates another <P> tag.

Line 28: Creates another horizonal rule tag.

Line 29: Closes our FORM tag.

Line 30: Closes out HTML, printing <BODY><HTML>.

Line 31: End of the Register subroutine.

Line 32: Begins the Welcome subroutine.

Line 33: Sets $visits to zero if there is currently nothing stored in it.

Line 34: Increments $visits. I know that we just set it to zero, but if you are viewing the page that the information is on, you couldn't have visited it zero times. So, visits will always be at least one once you get beyond this point.

Line 35: Creates a variable called $cookie_name that we will use for our name cookie. Notice that I passed it NAME, VALUE, and EXPIRES

  • Name is what we call the cookie.
  • Value is what we set the value of the cookie to.
  • Expires tells the cookie when to expire. 
I chose to expire this cookie in 3 days, so I set it to +3d. The expires tag can be tricky if you do it manually (if you read the cookie specification document, you will see what I mean), if you use the CGI module, it is a piece of cake.

Line 36: Creates a variable called $cookie_visits that we will use for our "visits" cookie. The same information that applied in the previous line applies here as well.

Line 37: Prints our header, like we did on Line 14, but this time we pass it the cookies. This is how we set the cookies on the user's browser.

Line 38: Prints the HTML to start a page, putting "Cookie Example" in the TITLE tag.

Line 39: Begins a <CENTER> tag.

Line 40: Creates the page heading using Arial FONT and a SIZE of 6.

Line 41: Creates another horizonal rule tag.

Line 42: Sets our FONT to ARIAL with a size of 3.

Line 43: Displays our welcome message to the user, in bold, and tells the user how many times he or she has visited the site.

Lines 44-49: Print some text to the Web page. By placing it inside the p subroutine, it wraps the text in <P> and </P> tags.

Line 50: Creates another horizonal rule tag.

Line 51: Closes the FONT tag from line 42.

Line 52: Closes the CENTER tag from line 39.

Line 53: Closes the HTML tag, see line 30.

Line 54: Ends the Welcome subroutine.

Wrapping It Up 

As you can see, cookies are not that difficult. They can add numerous features such as personalization to otherwise static Web pages and make visiting your sites more enjoyable and interesting for users. There are many applications for cookies. You could have a cookie store user preferences, such as colors and layout, so they can customize their view of your Web page. You can bring users directly to information that they specify they are interested in, filtering a large collection of information into something specifically tailored to them.

Cookies are very often used in conjunction with a database on the Web server which stores more details, hopefully securely, than can be stored in the limited space allowed by a cookie. The possibilities for cookies are numerous, and many cool things are being done on the Web using cookies today.

Here are some resources for more information about cookies:

WebReview articles about cookies

Netscape's cookie specification

Yahoo's Cookie Links

The CGI.pm Perl module documentation


Source Code for Serving Cookies to your Visitors
View and download the source to this week's program.
Next: CGI File Uploading

Web Review copyright © 1995-99 Songline Studios, Inc.
Web Techniques and Web Design and Development copyright © 1995-99 Miller Freeman, Inc.
ALL RIGHTS RESERVED