Mastering the Web
Contents
Website Planning Tutorial
Website Design Tutorial
HTML Tutorial
HTML Tables Tutorial
CGI Tutorial
JavaScript Tutorial
Perl Tutorials
CSS Tutorial
Installing a Web Server
Security Tutorial
HTML Cookies Tutorial
Web Tracking Tutorial
Download Free Programs
F.A.Q.

  1. Introduction
  2. Cookies with Perl and JavaScript
  3. Cookie parameters in JavaScript
  4. Issus concerning cookie acceptance
  5. What to do when cookies are disabled
  6. What to do with cookies

Download FWTLogstat1

Download FWTLogstat2

Cookies with Perl and JavaScript

Cookies with Perl

If you are programming in Perl, the easiest way to manage cookies is using the CGI module (CGI.pm) created by Lincoln Stein, which provides a number of useful subroutines (see this site's section on Perl subroutines). This module can be downloaded from CPAN (www.cpan.org). You must begin by creating an object called a query. For instance:

# create query object
$query = new CGI;

This query object has a "cookie" method to create and read cookies. The method has the following parameters: (a) a name; (b) a value; (c) a path that will be checked by the browser before sending the cookie; (d) an expiration date that can be replaced with a time interval such as "+1d" or "+1h". In addition, two more parameters can be used: (e) a domain name that will be also checked by the browser; (f) a secure flag that signals that the cookie should be transmitted only within a SSL session.

To create a cookie you must provide at least the name and the value of the cookie. The other parameters are optional. To read a cookie, the method is called with only the name of the cookie. An example of creation is:

# create query object
$query = new CGI;
# create cookie
$cookie = $query->cookie(-name=>"session_id", -value=>"1954897",
          -expires=>"+1h");

The module translates the "+1h" to a time that is one hour from the current time. This cookie must then be sent to the browser using the "header" method.

print $query->header(-cookie=>$cookie);

To read the cookie, you may use:

$session_identifier = $query->cookie(-name=>'session_id');

The cookie can also be incorporated to the HTTP headers using the 'redirect' method that functions similarly to the 'header' method. It produces an immediate redirection, so it must be the last thing the script does. An absolute URL should be used as the location.

As the session identifier, a random number of five digits can be used if the need for security is not paramount. Similarly, setting an expiration time of one hour will allow for the ordinary duration of a session. If the goal were to manage an electronic shopping cart, the settings would probably be different. Specifically, some other method should be used to generate the session identifier, which completely rules out the possibility of duplications. The Perl instructions that will compose the random number generator are:

$rnum = 100000 * rand;
$rint = int($rnum);
$str1 = sprintf("%05d", $rint);

The first instruction produces a floating-point number in the range 0 to 99999. The second makes an integer of it and the third pads nicely the integer with zeroes to the left.

A script that can be called to check for the existence of a session ID could be partially coded as follows.

$session_identifier = $query->cookie(-name=>'session_id');
if (!$session_identifier) {
    $session_identifier = "_void";
}

When the 'cookie' method is used without the 'value' parameter, it performs the function of retrieving the cookies of a page.

Cookies with JavaScript

A static Web page may have JavaScript code embedded that set and get cookies. This is done when the page is already retrieved from the Web server and is being rendered by the browser, so this code may effectively check if cookies are accepted or not. The code makes use of the "document.cookie" property, which is a string containing all the names and values of the cookies. The following routines will be handy for setting and getting cookies.

// Sets cookie values. Expiration date is optional.
//
function setCookie(name, value, expire) {
  document.cookie = name + "=" + escape(value)
  + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}
// Returns a cookie value, given the name of the cookie.
//
function getCookie(Name) {
  var search = Name + "="
  if (document.cookie.length > 0) { // if there are any cookies
    offset = document.cookie.indexOf(search)
    if (offset != -1) { // if cookie exists
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset)
      // set index of end of cookie value
      if (end == -1)
        end = document.cookie.length
      return unescape(document.cookie.substring(offset, end))
    }
  }
}

The 'escape' function accepts as argument a string coded using the ISO Latin-1 character set. It returns a string where each non-alphanumeric character has been replaced by a string of the form '%XX', where each X is a hexadecimal digit. The letters and numbers of the original string remain unchanged. The 'unescape' function performs the inverse of the previous function, with the difference that it not only translates expressions in hexadecimal, but also in decimal.

Using the functions 'setCookie' and 'getCookie', you may test if an identification cookie will be well received. While there is a property of the "navigator" object, window.navigator.cookieEnabled, that could be used to this end, it will not work flawlessly with all browsers in all circumstances. Therefore, you may as well take the straightforward approach of giving the user a test cookie, and trying to get it back. You should, however, test this procedure with the browser or browsers that your users will most likely use, and with the different settings that these browsers permit with respect to cookies.

The following code should be included within the body of the page.

// writes a cookie
var today = new Date();
var expires = new Date();
expires.setTime(today.getTime() + 1000*60);
setCookie("mycookie", "_TESTCOOKIE_", expires);
// reads the cookie
var yourcookie = getCookie("mycookie");
if (yourcookie != null)
     document.write("Cookies are enabled");
else
     document.write("Cookies are NOT enabled");

The cookie is set with a life of one minute; the constant 1000*60 is equal to 60,000 milliseconds or 60 seconds. The cookie is presently read and an action is taken according to the result of the reading.

Instead of writing to the page the result of your inquiry, you may want to redirect the user's browser to a different page depending on the result of the test.

A little caution may be necessary when using this method, as some browsers may respond inappropriately. It has been reported that a main browser accepts cookies even when they are nominally disabled through the preferences dialog. In this case a two-page method should be used as is later discussed.

Previous | Contents | Next

| HOME | FEEDBACK | BOOKMARK |
Build your Website
© 1999-2008 Hector Castro -- All rights reserved

If your doubt is not answered in this site, please use the
contact form .
I'll answer as soon as posible.
I can help you using instant messaging. To schedule a meeting, please use the
meeting form.
You will find the late news about the free programs offered here on my blog
Free Webmaster Tools
You can get news about updates to my free programs through this
RSS feed.

www.great-web-info.com