Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 4. Cookies > A Sample Cookie Program

4.3. A Sample Cookie Program

Example 4-1 is a CGI script called configure.cgi that generates pages such as Figure 4-1. When you call this script’s URL, you are presented with the fill-out form shown above. You can change the page’s background color, the text size and color, and even customize it with your name. The next time you visit this page (even if you’ve closed the browser and come back to the page weeks later), it remembers all of these values and builds a page based on them.

Example 4-1. The configure.cgi script

00 #!/usr/bin/perl
02 use CGI qw(:standard :html3);
04 # Some constants to use in our form.
05 @colors = qw/aqua black blue fuchsia gray green lime maroon navy olive
                purple red silver teal white yellow/;
06 @sizes = ("<default>", 1..7);
08 # Recover the "preferences" cookie.
09 %preferences = cookie('preferences');
11 # If the user wants to change the name or background color, they can
12 foreach ('text', 'background', 'name', 'size') {
13     $preferences{$_} = param($_) || $preferences{$_};
14 }
16 # Set some defaults
17 $preferences{background} = $preferences{background} || 'silver';
18 $preferences{text}       = $preferences{text} || 'black';
20 # Refresh the cookie so that it doesn't expire.
21 $the_cookie = cookie( -name => 'preferences',
22                      -value => \%preferences,
23                       -path => '/',
24                    -expires => '+30d');
25 print header(-cookie => $the_cookie);
27 # Adjust the title to incorporate the user's name, if provided.
28 $title = $preferences{name} ? "Welcome back, $preferences{name}!"
                               : "Customizable Page";
30 # Create the HTML page, controlling the background color and font size.
31 #
32 print start_html(  -title => $title,
33                  -bgcolor => $preferences{background},
34                     -text => $preferences{text});
36 print basefont({SIZE=>$preferences{size}}) if $preferences{size} > 0;
38 print h1($title),<<END;
39 You can change the appearance of this page by submitting
40 the fill-out form below. If you return to this page any time
41 within 30 days, your preferences will be restored.
42 END
43 ;
44 # Create the form.
45 print hr,
46       start_form,
48       "Your first name: ",
49       textfield(   -name => 'name',
50                 -default => $preferences{name},
51                    -size => 30), br,
52       table(
53             TR(
54                td("Preferred"),
55                td("Page color:"),
56                td(popup_menu(   -name => 'background',
57                               -values => \@colors,
58                              -default => $preferences{background})
59                  )
60               ),
61             TR(
62                td(''),
63                td("Text color:"),
64                td(popup_menu(   -name => 'text',
65                               -values => \@colors,
66                              -default => $preferences{text})
67                  )
68               ),
69             TR(
70                td(''),
71                td("Font size:"),
72                td(popup_menu(   -name => 'size',
73                               -values => \@sizes,
74                              -default => $preferences{size})
75                  )
76               )
77            ),
78       submit(-label => 'Set preferences'),
79       end_form,
80       hr;
82 print a({HREF => "/"}, 'Go to the home page');


Figure 4-1. A cookie-aware web page

This script recognizes four CGI parameters used to change the configuration:


Set the background color.


Set the text color.


Set the size to the indicated value (1–7).


Set the username.

Usually these parameters are sent to the script via the fill out form that it generates, but you could set them from within a URL this way:


Let’s walk through the code. Line 2 imports the CGI library, bringing in both the standard method calls and a number of methods that generate HTML3-specific tags. Next we define a set of background colors and sizes. The choice of colors may seem capricious, but it’s not: These are the background colors defined by the HTML 3.2 standard, and they’re based on the original colors used by the IBM VGA graphics display.

Line 9 is where we recover the user’s previous preferences, if any. We use the cookie method to fetch a cookie named “preferences”, and store its value in a like-named hash.

In lines 12 through 14, we fetch the CGI parameters named text, background, name, and size. If any of them are set, it indicates that the user wants to change the corresponding value saved in the browser’s cookie. We store changed parameters in the %preferences hash, replacing the original values.

Line 17 and 18 set the text and background colors to reasonable defaults if they can’t be found in either the cookie or the CGI script parameters.

Lines 21 through 25 generate the page’s HTTP header. First, we use the cookie method to create the cookie containing the user’s preferences. We set the expiration date for the cookie for 30 days in the future so that the cookie will be removed from the browser’s database if the user doesn’t return to this page within that time. We also set the optional -path parameter to /. This makes the cookie valid over our entire site so that it’s available to every URL the browser fetches. Although we don’t take advantage of this yet, it’s useful if we later decide that these preferences should have a site-wide effect. Lastly, we emit the HTTP header with the -cookie parameter set.

In lines 30 to 36 we begin the HTML page. To make it personalizable, we base the page title on the user’s name. If it’s set, the title and level 1 header both become “Welcome back <name>!” Otherwise, the title becomes an impersonal “Customizable page.” Line 32 calls the start_html method to create the top part of the HTML page. It sets the title, the background color and the text color based on the values in the %preferences array. Line 36 sets the text size by calling the basefont method. This simply generates a <BASEFONT> HTML tag with an appropriate SIZE attribute.

Lines 38 and up generate the content of the page. There’s a brief introduction to the page, followed by the fill-out form used to change the settings. All the HTML is generated using “shortcuts,” in which tags are generated by like-named method calls. For example, the hr method generates the HTML tag <HR>. As shown in the first column in this series, we start the fill-out form with a call to start_form, create the various form elements with calls to textfield, popup_menu, and submit, and close the form with end_form.

When I first wrote this script, the popup menus and popup menus in the form didn’t line up well. Because all the elements were slightly different widths, everything was crooked. To fix this problem, I used the common trick of placing the form elements inside an invisible HTML3 table. Assigning each element to its own cell forces the fields to line up. You can see how I did this in lines 52 through 77, where I define a table using a set of shortcuts. An outer call to table generates the surrounding <TABLE> and </TABLE> tags. Within this are a series of TR methods, each of which generates a <TR> tag. (In order to avoid conflict with Perl’s built-in tr/// operator, this is one instance where uses uppercase rather than lowercase shortcut names.) Within each TR call, in turn, there are several td calls that generate the <TD> (table data) cells of the HTML table.

Fortunately, my text editor auto-indents nicely, making it easy to see the HTML structure.

On a real site, of course, you’d want the user’s preferences to affect all pages, not just one. This isn’t a major undertaking; many modern web servers now allow you to designate a script that preprocesses all files of a certain type. You can create a variation on the script shown here that takes an HTML document and inserts the appropriate <BASEFONT> and <BODY> tags based on the cookie preferences. Now, just configure the server to pass all HTML documents through this script, and you’re set.

In the next article, Doug MacEachern and I introduce mod_perl, a Perl interpreter embedded inside the Apache web server.

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint