Docstoc

Perl_16_Session Tracking and Cookies

Document Sample
Perl_16_Session Tracking and Cookies Powered By Docstoc
					             Chapter 16 – Session Tracking and
                          Cookies
        Outline
        16.1           Introduction
        16.2           Uses of Storing Data
        16.3           Methods of Storing Data
        16.4           Query Strings
        16.5           Hidden Fields
        16.6           Cookies
        16.7           Server-side Files
        16.8           Example: Shopping Cart




 2001 Prentice Hall, Inc. All rights reserved.
                                            16.1 Introduction

      • HTTP
              – After server sends reply connection is closed
                     • Client can send data only once
                     • Client can receive data only once per request
              – Multiple interactions require linked pages
                     • Series of calls
                     • Store data between calls




 2001 Prentice Hall, Inc. All rights reserved.
                                 16.2 Uses of Storing Data

      • e-commerce
              – Online stores
              – User information needs to be maintained
                     • Interactive
                     • Customization
                         – Features
                         – Colors




 2001 Prentice Hall, Inc. All rights reserved.
                            16.3 Methods of Storing Data

      • Storing data
              – Client
                     • Cookies
                        – Store small amounts of text
                        – Can be disabled
              – Server
                     • Store files on server
                         – Best way
                         – May require large amounts of space on the server
              – Browser
                     • Can store data
                     • Can pass data from one to another
                     • Only non vital data

 2001 Prentice Hall, Inc. All rights reserved.
                                          16.4 Query Strings

      • Query String
              – Sent to the server attached to the request
                     • Same as a get request
              – Question mark at end of URL followed by information being
                sent in key-value pairs
              – Security issue
                     • Anyone can change the query string manually
                         – Change the URL arguments
                     • Someone could input values that do not make sense




 2001 Prentice Hall, Inc. All rights reserved.
 1   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 2   <!-- Fig. 16.1: fig16_01.html -->
                                                                                          Outline
 3   <!-- Web page offering different color options. -->
 4                                                                                  fig16_01.html
 5   <html>
 6      <head>
 7          <title>Preserving State Through Query Strings</title>
 8      </head>
 9
10     <body>
11         <p>Which Style do you Prefer?</p>
12         <table bgcolor = "#ffffff">
13              <tbody>                                  Outputs the Perl program
14                   <tr>                                with normal style
15                        <td>
16                             <font color = "#000000">Normal Style</font>
17                        </td>
18                        <td>
19                             <a href = "/cgi-bin/fig16_02.pl?type=normal">
20                             <font color = "#0000ff">Click here</font>
21                        </td>
22                   </tr>
23              </tbody>
24         </table>
25         <br/>
26         <table bgcolor = "#dddddd">
27              <tbody>
28                   <tr>
29                        <td>
30                             <font color = "#000000">Dark Style</font>
31                        </td>
 2001 Prentice Hall, Inc. All rights reserved.
32                        <td>                                                         Outline
33                             <a href = "/cgi-bin/fig16_02.pl?type=dark">
34                             <font color = "#002060">Click here</font>
35                        </td>
                                                                                    fig16_01.html
36                   </tr>
37              </tbody>
                                                              Outputs the Perl program
38         </table>
39         <br/>
                                                              with dark style
40         <table bgcolor = "#5555ff">
41              <tbody>
42                   <tr>
43                        <td>
44                             <font color = "#ee3333">Bright Style</font>
45                        </td>
46                        <td>
47                             <a href = "/cgi-bin/fig16_02.pl?type=bright">
48                             <font color = "#ffff00">Click here</font>
49                        </td>
50                   </tr>
51              </tbody>
                                                     Outputs the Perl program
52         </table>                                  in a bright style
53         <br/>
54         <table bgcolor = "#ffffc0">
55              <tbody>
56                   <tr>
57                        <td>
58                             <font color = "#ee82ee">Another Style</font>
59                        </td>
60                        <td>
 2001 Prentice Hall, Inc. All rights reserved.
61                             <a href = "/cgi-bin/fig16_02.pl?type=another">          Outline
62                             <font color = "#3cb371">Click here</font>
63                        </td>                                                 fig16_01.html
64                    </tr>
65               </tbody>                            Outputs the perl program
66           </table>                                in a another style
67           <br/>
68      </body>
69 </html>

                                                                                Program Output




  2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                 Outline
 2   # Fig. 16.2: fig16_02.pl
 3   # Create a page with a specified style.
 4
                                                                               fig16_02.pl
 5   use strict;
 6   use warnings;
 7   use CGI qw( :standard );
 8
 9   print( header() );
10
                                        Used to retrieve the chosen style
11   my $type = param( "type" );
12
13   my %colors = ( "normal" => [ "#ffffff", "#000000", "#0000ff" ],
14      "dark" => [ "#dddddd", "#000000", "#002060" ],
15      "bright" => [ "#5555ff", "#ee3333", "#ffff00" ],         A hash with the style as a key and
16      "another" => [ "#ffffc0", "#ee82ee", "#3cb371" ] );      the value as an array of colors to
17                                                                    that style
18   my $style = $colors{ $type };
19   my @style = @{ $style };                  The desired list of colors is
20                                             then stored into @style
21 print <<HTML;
22 <html><head><title>Your Style Page</title></head>
23 <body bgcolor = "$style[ 0 ]" text = "$style[ 1 ]"
24     link = "$style[ 2 ]" vlink = "$style[ 2 ]">
25 <p>This is your style page.</p>                              Uses the @style array to set the
26 <p>You chose the colors.</p>                                 colors of the background, text,
27 <a href = "/fig16_01.html">Choose a new style.</a>           link, and vlink
28 </body></html>
29 HTML
 2001 Prentice Hall, Inc. All rights reserved.
                                                         Outline

                                                  fig16_02.pl
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
                                          16.5 Hidden Fields

      • Hidden fields
              – Used to keep track of user information through the browser
              – Not useful for vital or important data
                     • Easy to mimic or change




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                                Outline
 2   # Fig. 16.3: fig16_03.pl
 3   # Use hidden form fields to keep track of data.
 4
                                                                                           fig16_03.pl
 5   use warnings;
 6   use strict;
 7   use CGI qw( :standard );
 8
 9   my $data = param( "HIDDEN" );
                                                       Uses the CGI.pm’s param method
10   my $name = param( "NAME" );
11   my $value = param( "VALUE" );                     to get the values that were passed
12
13   $data .= "$name ";
14   $data .= "$value ";
                                             Adds the new data to the old data
15
16   print( header() );
17   print( start_html( -title => 'Using Hidden Fields' ) );
18
19   print <<Form;
20   <form method = "post" action = "fig16_03.pl">
21   <strong>Please enter the fields name: </strong>                             Transfers all old data
22   <input type = "TEXT" name = "NAME"><br>
                                                                                 through a hidden field
23   <strong>Please enter the fields value: </strong>
24   <input type = "TEXT" name = "VALUE"><br>
25   <input type = "HIDDEN" name = "HIDDEN" value = "$data">
26   <input type = "SUBMIT" value = "enter your data">
27   </form>
28   Form
29
 2001 Prentice Hall, Inc. All rights reserved.
30 my %values = split( ' ', $data );                                                   Outline
31
32 foreach ( keys( %values ) ) {                  Formats the information in $data
                                                                                   fig16_03.pl
33      print( p( "$_: $values{ $_ }" ) );        so it is output in a readable style
34 }
35
36 print( end_html() );



                                                                              Program Output




 2001 Prentice Hall, Inc. All rights reserved.
                                                         Outline

                                                  fig16_03.pl
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
                                                  16.6 Cookies

      • Cookies
              – Small text file sent by Web server
              – Written to user’s computer
              – Keep track of data
                     • How many times visited
                     • What purchased
                     • Personal data
              – Can be disabled
                     • Some see it as a security and privacy concern




 2001 Prentice Hall, Inc. All rights reserved.
 1   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 2   <!-- Fig. 16.4: fig16_04.html -->
                                                                                           Outline
 3   <!-- Web page to read in some data from the user. -->
 4                                                                               fig16_04.html
 5   <html>
 6      <head>
 7          <title>Writing a cookie to the client computer</title>
 8      </head>
 9                                                               Creates a Web form that
10      <body>
                                                                 takes data from the user and
11         <font face = "arial,sans-serif" size = 2>
12                                                               then passes it to another form
13               <font size = +2>
14                  <b>Click Write Cookie to save your cookie data.</b>
15               </font><br>
16
17               <form method = "post" action = "/cgi-bin/fig16_05.pl">
18                  <strong>Name:</strong><br>
19                  <input type = "text" name = "name"><br>
20
21                    <strong>Height:</strong><br>                  Sends the data to fig16_05.pl
22                    <input type = "text" name = "height"><br>
23
24                    <strong>Favorite Color</strong><br>
25                    <input type = "text" name = "color"><br>
26
27                  <input type = "SUBMIT" value = "Write Cookie">
28               </form>
29
30     </body>
31 </html>
 2001 Prentice Hall, Inc. All rights reserved.
                                                         Outline

                                                  fig16_04.html
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                                Outline
 2   # Fig. 16.5: fig16_05.pl
 3   # Program to write a cookie to a client’s machine.
 4                                                                                        fig16_05.pl
 5   use strict;
 6   use warnings;
 7   use CGI qw( :standard );
 8
 9   my $name = param( "name" );
10   my $height = param( "height" );
11   my $color = param( "color" );
12
13   my $expires = "Monday, 11-JUN-01 16:00:00 GMT";                      Contains the expiration
14                                                                        date of the cookie
15   print( "Set-Cookie: Name=$name; expires=$expires; path=\n" );
16   print( "Set-Cookie: Height=$height; expires=$expires; path=\n"
);
17   print( "Set-Cookie: Color=$color; expires=$expires; path=\n" );
18
19   print( header(), start_html( "Cookie Saved" ) );                       Creates 3 cookies to store
20                                                                          the user entered data.
21   print <<End_Data;
22   <font face = "arial,sans-serif" size = 3>
23   The cookie has been set with the following data:<br><br>
24
                                                  Indicates that the cookie was written
25   <font color = blue>Name:</font> $name<br>
26   <font color = blue>Height:</font> $height<br>
27   <font color = blue>Favorite Color:</font>
28      <font color = $color> $color<br></font><br>
29
 2001 Prentice Hall, Inc. All rights reserved.
30 Click <a href = "fig16_06.pl">here</a>                Outline
31      to read saved cookie.
32 End_Data
                                                  fig16_05.pl
33
34 print( end_html() );


                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                          Outline
 2   # Fig. 16.6: fig16_06.pl
 3   # Program to read cookies from the client's computer.
 4
                                                                                     fig16_06.pl
 5   use strict;
 6   use warnings;
 7   use CGI qw( :standard );
 8
 9   print(   header(), start_html( "Read cookies" ) );
10   print(   "<font face = \"arial,sans-serif\" size = 3>" );
11   print(   strong( "The following data is saved in a cookie " ) );
12   print(   strong( "on your computer." ) );
13   print(   br(), br() );
14
15   my %cookies = readCookies();                 Calls the readCookies function
16
17   print( "<table border = \"5\" cellspacing = \"0\" " );
18   print( "cellpadding = \"10\">" );
19                                                       Goes through all the keys printing
20   foreach (     "Name", "Height", "Color" ) {         each value into an HTML table
21      print(     "<tr>" );
22      print(     "   <td bgcolor = #aaaaff>$_</td>" );
23      print(     "   <td bgcolor = #aaaaaa>$cookies{ $_ }</td>" );
24      print(     "</tr>" );
25   }
26
27   print( "</table>" );
28   print( end_html() );
29
 2001 Prentice Hall, Inc. All rights reserved.
30 sub readCookies                                                                   Outline
31 {
32    my @cookieArray = split( "; ", $ENV{ 'HTTP_COOKIE' } );
33    my $cookieName;
                                                                               fig16_06.pl
34    my $cookieValue;
35    my %cookieHash;                      Split is used to get the original
36                                         name and value of the pair
37    foreach ( @cookieArray ) {
38       ( $cookieName, $cookieValue ) = split( "=", $_ );
39       $cookieHash{ $cookieName } = $cookieValue;
40    }
41
42    return %cookieHash;
43 }
                              The pairs are then stored into a
                                             hash and returned




 2001 Prentice Hall, Inc. All rights reserved.
                                                         Outline

                                                  fig16_06.pl
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
                                      16.7 Server-side Files

      • Server-side files
              – Store user files on the server machine
              – Most secure way of storing files
              – One downside is the requirement of large amounts of disk
                space
              – Need a way to distinguish from anonymous users




 2001 Prentice Hall, Inc. All rights reserved.
 1   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">               Outline
 2   <!-- Fig. 16.7: fig16_07.html -->
 3   <!-- Web page to read in some data that will be -->
 4   <!-- entered into a file. -->
                                                                            fig16_07.pl
 5
 6   <html>
 7      <head>
 8          <title>
 9             Please enter your contact information.
10          </title>
11      </head>
12
13      <body>
14         <p>
                                                         Calls the program fig16_08.pl
15              Please enter your information in the form below:
16           </p>
17           <form method = "post" action = "/cgi-bin/fig16_08.pl">
18              <strong>
19                 <p>
20                     First name:
21                     <input type = "text" name = "first" size = "10">
22                     Last name:
23                     <input type = "text" name = "last" size = "15">
24                 </p>
25                 <p>
26                     Address:
27                     <input type = "text" name = "address" size = "25">
28                        <br/>
  2001 Prentice Hall, Inc. All rights reserved.
29                        Town:                                                            Outline
30                        <input type       = "text" name = "town" size = "10">
31                        State:
32                        <input type       = "text" name = "state" size = "2">
                                                                                     fig16_07.pl
33                        <br/>
34                        Zip Code:
35                        <input type       = "text" name = "zip" size = "5">
36                        Country:
37                        <input type       = "text" name = "country" size = "10">
38             </p>
39             <p>
40                 E-mail Address:
41                 <input type = "text" name = "email">
42             </p>
43             <input type = "submit" value = "Enter">
44             <input type = "reset" value = "Clear">
45       </form>
46    </body>
47 </html>




  2001 Prentice Hall, Inc. All rights reserved.
                                                         Outline

                                                  fig16_07.pl
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                    Outline
 2   # Fig. 16.8: fig16_08.pl
 3   # Program to enter user's contact information into a
 4   # server-side file.                                                          fig16_08.pl
 5
 6   use    strict;
 7   use    warnings;
 8   use    CGI qw( :standard );
 9   use    Fcntl;
10
11   my    $first = param( 'first' );
12   my    $last = param( 'last' );
13   my    $address = param( 'address' );
14   my    $town = param( 'town' );               Reads all the parameters that
15   my    $state = param( 'state' );             were posted by the client
16   my    $zip = param( 'zip' );
17   my    $country = param( 'country' );
18   my    $email = param( 'email' );
19
20   my $name;
21   my @characters = ( 'a' .. 'z', '0' .. '9' );
22
23   do {
24
25         for ( 1 .. 10 ) {                  Creates a randomly generated file name
26            my $number = rand( 36 );
27            $name .= $characters[ $number ]; Loops until an original file name is
28         }                                   generated, and then makes the file
29   }
30   until sysopen( FILE, "$name.txt", O_WRONLY | O_EXCL | O_CREAT );
 2001 Prentice Hall, Inc. All rights reserved.
31                                                                                             Outline
32    print(     FILE   "$first $last\n" );
33    print(     FILE   "$address\n" );
34    print(     FILE   "$town $state $country $zip\n" );
                                                                                      fig16_08.pl
35    print(     FILE   "$email\n" );
36    close(     FILE   ) or die( "Cannot close file: $!" );
                                                                    Outputs the information of the file
37
38    print( header() );
39    print( start_html( -title => 'Contact Information is entered' ) );
40 print( strong(             "The following information has been stored:\n" ));
41
42    print( "<table><tbody>" );
43
44    print(     Tr(   td(   "First Name: " ), td( $first ) ) );
45    print(     Tr(   td(   "Last Name: " ), td( $last ) ) );
46    print(     Tr(   td(   "Address: " ), td( $address ) ) );
47    print(     Tr(   td(   "Town: " ), td( $town ) ) );
48    print(     Tr(   td(   "State: " ), td( $state ) ) );
49    print(     Tr(   td(   "Zip Code: " ), td( $zip ) ) );
50    print(     Tr(   td(   "Country: " ), td( $country ) ) );
51    print(     Tr(   td(   "E-mail: " ), td( $email ) ) );
52
53    print( "</tbody></table>" );
54                                                      Displays the file name for the user
55    print( p( "Your ID number is $name" ) );
56
57    print( end_html() );

      2001 Prentice Hall, Inc. All rights reserved.
                                                         Outline

                                                  fig16_08.pl
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
                                      16.7 Server-side Files




             Jane Doe
             123 Main Street
             Boston MA USA 12345
             jane@doe.com




        Fig. 16.9 Contents of rnvonpq849.txt.


 2001 Prentice Hall, Inc. All rights reserved.
                           16.8 Example: Shopping Cart

      • Shopping Carts
              – Allow users to store items the want to buy
              – The user pays for them when they “check out”




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                          Outline
 2   # Fig. 16.10: fig16_10.pl
 3   # Script to login to a Web page.
 4                                                                                 fig16_10.pl
 5   use    strict;
 6   use    warnings;
 7   use    CGI qw( :standard );
 8   use    Digest::MD5;
 9   use    Digest::MD5 qw( md5_hex );
10
11   # parameters are read in from the previous Web page
12   my $password = param( "password" );
13   my $user = param( "user" );
14   my $new = param( "new" );
15
16   if ( param( "new" ) ) {                      Checks to see if the new parameter exists
17      my @search1;
18
19         # Write nothing to the cookie ---
20                                                   cart
           # Users just logging in will not have aanew cookie for
                                         Creates                      the
21         writeCookie();                user, clears cart if empty
22
23         # Encryption of password so that it is protected
24         my $encrypt;
25         my $digestObject = Digest::MD5->new();
26         $digestObject->add( "$password" );       Encrypts       the user’s password
27         $encrypt = $digestObject->digest();
28
29         print( header() );
30         print( start_html() );
 2001 Prentice Hall, Inc. All rights reserved.
31                                                                                              Outline
32     open( LOG, "<log.txt" ) or die( "Cannot open: $!" );
33
34     while ( <LOG> ) {
                                                Checks for duplications                 fig16_10.pl
35         @search1 = split( "\t" );
                                                The file that contains all the
36                                              usernames and passwords
37         # If this username is found in the log,
38         # it has already been taken
39         if ( $search1[ 0 ] eq $user ) {
40              print( "This name has already been taken.<br>" );
41              print( "<a href = \"fig16_10.pl\">Try again</a>." );
42              print( end_html() );
43              exit;
44         }
45     }
46     close( LOG ) or die( "Cannot close: $!" );
47
48     # Add new user to the file
49     open( LOG, ">>log.txt" ) or die( "Cannot open: $!" );
50     print( LOG "$user\t$encrypt\n" );
51     close( LOG ) or die( "Cannot close: $!" );
52                                                                                Brings the user to a page
53     print( i( "Your information has been processed." ) );                      to begin shopping
54     print( br() );
55     print( "<a href = \"fig16_11.pl\">Start Shopping!</a>" );
56     print( end_html() );
57 }
                                                             Checks to see if the
58 elsif ( param( "password" ) ) {
59     my $found = 0;                                        password parameter exists
60     my @search2;
61
 2001 Prentice Hall, Inc. All rights reserved.
62         writeCookie();                                                                         Outline
63         print( header(), start_html() );
64
                                                                                            fig16_10.pl
65         my $digestObject = Digest::MD5->new();
                                                                Encrypt the password
66         $digestObject->add( "$password" );
67         my $encrypt = $digestObject->digest();
68
69         # Search the log for this person
70         open( LOG, "<log.txt" ) or die( "Cannot open: $!" );
71
72         while ( <LOG> ) {                           Find the user name in the log file
73             @search2 = split( "\t" );
74             chomp( $search2[ 1 ] );
75
76             if ( $search2[ 0 ] eq $user ) {
77
78                  # The password entered is correct
79                  if ( $search2[ 1 ] eq $encrypt ) {
80                      print( "Thank you for returning, $user!" );
81                      print( br() );
82                      print( "<a href = \"fig16_11.pl\">Start Shopping!" );

83                      print( "</a>" );
84                      $found = 1;                      Lets the user shop after
85                      last;                            verifying the password
86                  }
      2001 Prentice Hall, Inc. All rights reserved.
87              else {                                                                             Outline
88                   print( i( "You have entered an incorrect " ) );
89                   print( i( "password. Please try again." ) );
90                   print( br() );                                                       fig16_10.pl
91                   print( "<a href = \"fig16_10.pl\">Back to login" );
92                   print( "</a>" );
93                   $found = 1;
94                   last;
95              }                                 Returns the user to the login
96         }                                      for an incorrect password
97     }
98     close( LOG );
99
100    # This person is not found in the log
101    # They are new or have entered an incorrect username
102    if ( $found == 0 ) {
103        print( "You are not a registered user.<br>" );
104        print( "<a href = \"fig16_10.pl\">Register</a>" );
                                                                                If the user is not found the
105    }                                                                        program registers them
106    print( end_html() );
107 }
108 else {                                 Executed when the program is first started
109    print( header() );
110    print( start_html( -title => 'Please login' ) );
111
112    print <<"          FORM";
113
114    <p>Please login.</p>
115
116    <form method = "post" action = "fig16_10.pl"><p>
117
 2001 Prentice Hall, Inc. All rights reserved.
118    User Name: <input type = "text" name = "user"><br/>                 Outline
119    Password: <input type = "password" name = "password"><br/>
120    New? <input type = "checkbox" name = "new" value = "1"></p>
121                                                                  fig16_10.pl
122    <input type = "submit" value = "login">
123    </form>
124                           Creates an HTML form that
125    FORM
                              allows the user to enter a name
126
127    print( end_html() );
                              and password or check the ‘new’
128 }                         box
129
130 # Function writeCookie creates a cookie containing
131 # the array that was passed in during the function call
132 sub writeCookie
133 {                                       Creates a new cookie
134    my $expires = "Monday, 11-JUN-01 16:00:00 GMT";
135    print( "Set-Cookie: " );
136    print( "CART=", join( "\t", @_ ), "; expires=$expires\n" );
137    return;
138 }




 2001 Prentice Hall, Inc. All rights reserved.
                                                        Outline

                                                  fig16_10.pl




 2001 Prentice Hall, Inc. All rights reserved.
                                                        Outline

                                                  fig16_10.pl




 2001 Prentice Hall, Inc. All rights reserved.
                                                        Outline

                                                  fig16_10.pl




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                       Outline
 2   # Fig. 16.11: fig16_11.pl
 3   # Add or remove a book from cart and print cart contents
 4                                                                   fig16_11.pl
 5   use warnings;
 6   use strict;
 7   use CGI qw( :standard );
 8
 9   my @cart = readCookie();
10   my $remove = param( "remove" );
11   my @book;
12
13   if ( $remove ) {      Removing an item       from the cart
14      my $number = param( "number" );
15
16       # The book is removed from the cart array
17       @book = splice( @cart, 4 * ( $number - 1 ), 4 );
18
19       # The new array is written to the cookie
20       writeCookie( @cart );
21       print( header() );
22       print( start_html( "Book removed" ) );
23
24       print <<"   End_Remove";
25       <center><p>The book <i>$book[0]</i> has been removed.</p>
26       <a href = "fig16_11.pl">Return to cart</a>
27       <br>
28       <a href = "fig16_13.pl">Sign Out</a>
29       End_Remove
30
31   }
 2001 Prentice Hall, Inc. All rights reserved.
32 else {                                                                              Outline
33     @book = param( "newbook" ); When adding an item to the cart
34
35     # Add the book the user wants to the cart array                             fig16_11.pl
36     push( @cart, @book );
37                                              Creates a new book to be
38     # If there is nothing in the cart, added to the cart
39     # simply show the items for sale
40     if ( !@cart ) {
41         print( redirect( "fig16_12.pl" ) );
42         exit;
43     }
                                                         If the cart is empty the user is
44                                                       directed to fig16_12.pl
45     # Change cookie so it has the new entry
46     writeCookie( @cart );
47     print( header() );                             Update the cookie
48     print( start_html( "Shopping Cart" ) );
49
50     print <<"          End_Add";
51     <center><p>Here is your current order.</p>            Displays the book for the user
52     <table border = "1" cellpadding = "7">
53         <tr>
54              <th>Item</th>
55              <th>Name</th>
56              <th>Year</th>
57              <th>ISBN</th>
58              <th>Price</th>
59              <th></th>
60         </tr>
61     End_Add
62
 2001 Prentice Hall, Inc. All rights reserved.
63    my $counter = 1;                                                                  Outline
64    my $total = 0;
65    my @cartCopy = @cart;
                                                                              fig16_11.pl
66
67    # print out the cart for the user
68    while ( @book = splice( @cartCopy, 0, 4 ) ) {
69       print( "<tr><form method = \"post\"" );
70       print( "action = \"fig16_11.pl\">" );
71       print( "<td>$counter</td>" );                      Displays the cart for the user
72        print(   "<td>$book[ 0 ]</td>" );
73        print(   "<td>$book[ 1 ]</td>" );
74        print(   "<td>$book[ 2 ]</td>" );
75        print(   "<td>$book[ 3 ]</td>" );
76        print(   "<td>", submit( "Remove" ), "</td>" );
77
78        param( "remove", 1 );      # set "remove" variable to true
79        param(   "number", $counter );   # book number to remove
80        print(   hidden( "remove" ) );
81        print(   hidden( "number" ) );
82        print(   "</form></tr>" );
83
84        $book[ 3 ] =~ s/\$//;            # remove $ sign
85        $total += $book[ 3 ];            # add price        Takes a tally of the total price
86        $counter++;
87    }
88
89     print( "<tr><th colspan = \"4\">Total Order</th><th>" );
90     printf( "\$%0.2f", $total );             # print the total
 2001 Prentice Hall, Inc. All rights reserved.
91                                                                           Outline
92       print( "</tr>" );
93       print( "</table><br>" );
                                                                       fig16_11.pl
94       print( "<a href = \"fig16_12.pl\">Buy more books</a>" );
95       print( br() );
96       print( "<a href = \"fig16_13.pl\">Sign out</a>" );
97 }
98 print( end_html() );
99
100 sub writeCookie
101 {                                         Creates a cookie
102      my $expires = "Monday, 11-JUN-01 16:00:00 GMT";
103      print( "Set-Cookie: " );
104      print( "CART=", join( "\t", @_ ), "; expires=$expires\n" );
105      return;
106 }
107
108 # Read the user's cookies
109 # Return the information from the CART cookie
110 sub readCookie
111 {                                         Reads the cookie
112      my @cookieValues = split( "; ", $ENV{ 'HTTP_COOKIE' } );
113      my $name;
114      my $value;
115      my @data;
116
 2001 Prentice Hall, Inc. All rights reserved.
117     foreach ( @cookieValues ) {                     Outline
118          ( $name, $value ) = split ( "=" );
119
                                                  fig16_11.pl
120          if ( $name eq "CART" ) {
121              @data = split( "\t", $value );
122              last;
123          }
124     }
125     return @data;
126 }




 2001 Prentice Hall, Inc. All rights reserved.
                                                        Outline

                                                  fig16_11.pl




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                  Outline
 2   # Fig. 16.12: fig16_12.pl
 3   # Reads books from a database and prints them in a table
 4                                                                            fig16_12.pl
 5   use warnings;
 6   use strict;
 7   use CGI qw( :standard );
 8
 9   my @data;
10
11   print( header(), start_html( "Book List" ) );
12
13   open( BOOKS, "catalog.txt" ) or
14      die( "The database could not be opened." );
15
16   print <<End_Begin;
                                                  Opens the catalog, which contains
17
18   <center>Books available for sale<br>
                                                  the books the user can buy
19
20   <a href = "fig16_13.pl">Sign Out</a><br>
21
22   <table border = "1" cellpadding = "7">
23   <tr>
24      <th>Name</th>
25      <th>Year</th>
26      <th>ISBN</th>
27      <th>Price</th>
28   </tr>
29
30   End_Begin
 2001 Prentice Hall, Inc. All rights reserved.
31                                                                                           Outline
32 # print books the user can buy
33 while ( <BOOKS> ) {
                                                  Outputs a table that                 fig16_12.pl
34
35      @data = split( "\t" );                       # Variable items
                                                  contains all the $_ assumed
36
37      print( "<form method = \"post\" action = \"fig16_11.pl\">"
);
38      param( "remove" , 0 );                    # The user is not removing a book,
39      param( "newbook", @data );                   # They are adding a book
40      print( hidden( "remove" ) );
41      print( hidden( "newbook"), "\n<tr>" );
42
43      foreach ( @data ) {
44           print( "<td>$_</td>" );                 # print data item within a cell
45      }
46
47      print( "<td>", submit( "Buy" ), "</td></tr></form>\n" );
48 }
49
                                                         A button the user can
50 print( "</table>" );
                                                         click on to buy the book
51
52 print( end_html() );
53 close( BOOKS ) or die( "Cannot close: $!" );




 2001 Prentice Hall, Inc. All rights reserved.
                                                        Outline

                                                  fig16_12.pl




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                 Outline
2    # Fig. 16.13: fig16_13.pl
3    # Web page used to sign user out.
                                                                            fig16_13.pl
4
5    use strict;
6    use warnings;
7    use CGI qw( :standard );
8
9    # Erase the user's cart information
10   writeCookie();               Clears the cookie thus
11                                emptying the users cart
12   print(   header() );
13   print(   start_html( -title => 'Logged out' ) );
14   print(   "You are now logged out." );                  Logs the user out of the program
15   print(   br(), "You will be billed accordingly." );
16
17   print( br(), "To login again, " );
18   print( "<a href = \"fig16_10.pl\">click here</a>." );
19
20   print( end_html() );
21
22   sub writeCookie
23 {
24     my $expires = "Monday, 11-JUN-01 16:00:00 GMT";
25     print( "Set-Cookie: " );
26     print( "CART=", join( "\t", @_ ), "; expires=$expires\n" );
27     return;
28 }
 2001 Prentice Hall, Inc. All rights reserved.
                                                        Outline

                                                  fig16_13.pl




 2001 Prentice Hall, Inc. All rights reserved.
                           16.8 Example: Shopping Cart




              Visual Basic 6 How to Program       1999    0-13-456955-5    $50.00
              C++ How to Program      1997        0-13-528910-6   $49.95
              C How to Program        1994        0-13-226119-7   $50.00
              Java How to Program     1997        0-13-899394-7   $39.95
              Java How to Program 2e 1999         0-13-012507-5   $50.00




        Fig. 16.14 Contents of catalog.txt.


 2001 Prentice Hall, Inc. All rights reserved.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:2
posted:2/10/2012
language:
pages:51