Chapter: Internet & World Wide Web HOW TO PROGRAM - Perl and CGI (Common Gateway Interface)

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Cookies and Perl

Cookies maintain state information for a particular client who uses a Web browser. Preserving this information allows data and settings to be retained even after the execution of a CGI script has ended.

Cookies and Perl


Cookies maintain state information for a particular client who uses a Web browser. Preserving this information allows data and settings to be retained even after the execution of a CGI script has ended. Cookies are used to record user preferences (or other information) for the next time a client visits a Web site. For example, many Web sites use cookies to store a client’s postal zip code. The zip code is used when the client requests a Web page to send, for instance, current weather information or news updates for the client’s region. On the server side, cookies may be used to help track information about client activity, to deter-mine which sites are visited most frequently or how effective certain advertisements and products are.


Microsoft Internet Explorer stores cookies as small text files saved on the client’s hard drive. The data stored in the cookies are sent back to the whenever the user requests a Web page from the server. The server can then serve XHTML content to the client, specific to the information stored in the cookie.


Figure 27.21 uses a script to write a cookie to the client’s machine. The fig27_21.html file is used to display an XHTML form that allows a user to enter a name, height and favorite color. When the user clicks the Write Cookie button, the script (Fig. 27.22) is executed.


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"



    <!-- Fig. 27.21: fig27_21.html -->




    <title>Writing a cookie to the client computer</title>


<body style = "font-face: arial">

<div style = "font-size: large;

font-weight: bold">

Click Write Cookie to save your cookie data.

</div><br />


<form method = "post" action = "cgi-bin/"

style = "font-weight: bold">

Name:<br />

<input type = "text" name = "name" /><br />

Height:<br />

<input type = "text" name = "height" /><br />

Favorite Color:<br />

<input type = "text" name = "color" /><br />

<input type = "submit" value = "Write Cookie" />





Fig. 27.21  XHTML document to read in cookie data from the user

The script (Fig. 27.22) reads the data sent from the client on lines 7– 9. Line 11 declares and initializes variable $expires to contain the expiration date of the cookie. The browser deletes a cookie after it expires. Lines 13–15 call function print to output the cookie information. We use the Set-Cookie: header to indicate that the browser should store the incoming data in a cookie. The header sets three attributes for each cookie: A name–value pair containing the data to be stored, the expiration date and the URL path of the server domain over which the cookie is valid. For this example, no path is given, making the cookie readable from anywhere within the server’s domain. Lines 21–40 create a Web page indicating that the cookie has been written to the client.



    # Fig. 27.22:

    # Program to write a cookie to a client’s machine.


    use CGI qw( :standard );


    $name = param( "name" );

    $height = param( "height" );

    $color = param( "color" );


      $expires = "Monday, 11-JUN-01 16:00:00 GMT";

      print( "Set-Cookie: Name=$name; expires=$expires; path=\n" );

      print( "Set-Cookie: Height=$height; expires=$expires; path=\n" );

      print( "Set-Cookie: Color=$color; expires=$expires; path=\n" );


      $dtd =

      "-//W3C//DTD XHTML 1.0 Transitional//EN\"



      print( header() );

print( start_html( { dtd => $dtd,

title => "Cookie Saved" } ) );

      print <<End_Data;

      <div style = "font-face: arial; font-size: larger">

      The cookie has been set with the following data:

      </div><br /><br />

      <span style = "color: blue">

      Name: <span style = "color: black">$name</span><br />

      Height: <span style = "color: black">$height</span><br />

      Favorite Color:</span>

      <span style = "color: $color"$color</span><br />

      <br />Click <a href = "">here</a>

      to read saved cookie.


      print( end_html() );


Fig. 27.22  Writing a cookie to the client


On lines 25–38 we see our first “here” document. Line 25 instructs the Perl interpreter to print the subsequent lines verbatim (after variable interpolation) until it reaches the End_Data label. This label consists simply of the identifier End_Data, placed at the beginning of a line, with no whitespace characters preceding it, and followed immediately with a newline. “Here” documents are often used in CGI programs to eliminate the need to call function print repeatedly. Notice that we use functions in the CGI library, as well as “here” documents, to create a clean program.


If the client is an Internet Explorer browser, cookies are stored in the Cookies direc-tory on the client’s machine. Figure 27.23 shows the contents of this directory prior to the execution of After the cookie is written, a text file is added to this list. The file cheryl@localhost[1].txt can be seen in the Cookies directory in Fig. 27.24. The domain for which the cookie is valid is localhost. The username cheryl, how-ever, is only part of the filename Internet Explorer uses for cookies and is not actually a part of the cookie itself. Therefore, a remote server, cannot access the username.


Figure 27.25 ( reads the cookie written in Fig. 27.22 and displays the information in a table. Environment variable HTTP_COOKIE contains the client’s cookies. Line 25 calls subroutine readCookies and places the returned value into hash %cookies. The user-defined subroutine readCookies splits the environment variable containing the cookie information into separate cookies (using split) and stores the cookies as distinct elements in @cookieArray (line 39). For each cookie in @cookie-Array, we call split again to obtain the original name–value pair—which, in turn, is stored in %cookieHash in line 43.


Note that the split function in line 42 makes reference to a variable named $_. The special Perl variable $_ is used as a default for many Perl functions. In this case, because no variable was provided in the foreach loop (line 41), $_ is used by default. Thus, in this example, $_ is assigned the value of the current element of @cookieArray as a foreach structure iterates through it.


Once %cookieHash has been created, it is returned from the function on line 46 (using the return keyword), and %cookies is assigned this value in line 25. A foreach loop (lines 28–32) then iterates through the hash with the given key names, printing the key and value for the data from the cookie in an XHTML table.



Fig. 27.23  Cookies directory before a cookie is written.




    # Fig. 27.25:

    # program to read cookies from the client's computer.


    use CGI qw( :standard );

    $dtd =

    "-//W3C//DTD XHTML 1.0 Transitional//EN\"



      print( header() );

print( start_html( { dtd => $dtd,

title => "Read Cookies" } ) );


print( div( { style => "font-face: arial;

font-size: larger;

font-weight: bold" },

"The following data is saved in a

cookie on your computer." ), br() );


print( "<table style = \"background-color: #aaaaaa\"

border = 5 cellpadding = 10

cellspacing = 0>" );

      %cookies = readCookies();

      $color = $cookies{ Color };


      foreach $cookieName ( "Name", "Height", "Color" ) {

print( Tr( td( { style => "background-color: $color" },

          $cookieName ),

          td( $cookies{ $cookieName } ) ) );


      print( "<table>" );

      print( end_html() );


      sub readCookies


      @cookieArray = split( "; ", $ENV{ 'HTTP_COOKIE' } );


      foreach ( @cookieArray ) {

      ( $cookieName, $cookieValue ) = split( "=", $_ );

      $cookieHash{ $cookieName } = $cookieValue;


      return %cookieHash;


Fig. 27.25  Output displaying the cookie’s content


It is important to note that users can disable cookies on their machines. There are a few ways to do this, but the most basic is to create a file similar to a cookie that would be stored on the server’s computer, rather than the client’s computer. For more information, the reader can visit the Web sites listed at the end of this chapter.


Operator Precedence Chart


This section contains the operator precedence chart for Perl (Fig. 27.26). The operators are shown in decreasing order of precedence, from top to bottom.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.