How Are Cookies Created and Read?

Cookies are set using a Set-cookie: HTTP header with five possible fields separated with a semicolon and a space.
These fields are:
cookie-name=cookie-value; -name of the cookie and its value (combined <4KB).
expiration=expiration-date; -the date the cookie will be deleted from the cookie file. You can delete a previously set cookie ahead of schedule by creating a second cookie with the same name, path, and domain, but with an expiration date in the past.
path=cookie-path; -combines with the domain name to determine when a browser should show a cookie to the server.
domain=server-domain; -used to determine when a browser should show a cookie to the server. Usually, cookies are created with the Web server's name without the www. For example, .foo.net instead of www.foo.net. Notice that the leading period is retained.
secure -ensures that the cookie will be sent back only to the server when a secure HTTP connection has been established.

When all of these elements are put together, they look like this:

     Set-Cookie: user_addr=ppp1.dialin.iupui.edu;
     expires=Wednesday, 09-Nov-99 00:00:00 GMT; path=/cgi-bin/;
     domain=.engr.iupui.edu; secure
==============================================================
Below is a perl script that both sets and read cookies. First, it will create four cookies and then it will read those cookies from the HTTP_COOKIE environment variable. Inside the HTTP_COOKIE environment variable, the cookies are delimited by a semicolon and a space. The cookie fields are separated by commas, and the name-value pairs are separated by equal signs. In order to use cookies, you need to parse the HTTP_COOKIE variable at three different levels.

     #!/usr/local/bin/perl -w
     use strict;
     my($expDate)   = "Wednesday, 09-Nov-99 00:00:00 GMT";
     my($theDomain) = ".engr.iupui.edu";
     my($path)      = "/cgi-bin/";
     setCookie("user", "dbewley", $expDate, $path, $theDomain);
     setCookie("user_addr", $ENV{'REMOTE_HOST'}, $expDate, $path, $theDomain)
         if defined($ENV{'REMOTE_HOST'});
     setCookie("flag", "black", $expDate, $path, ".iupui.edu");
     setCookie("car", "honda:accord:88:LXI:green", $expDate, $path, $theDomain);
     my(%cookies) = getCookies();
     print("Content-type: text/html\n\n");
     print("<html><head><title>cookies</title></head><bosy><h1>Cookies</h1>");
     print("<table>");
     foreach (sort(keys(%cookies))) {
         print("<tr><td>$_</td><td>$cookies{$_}</td></tr>");
     }
     print("</table></body></html>");

     sub setCookie {
         my($name, $val, $exp, $path, $dom, $secure) = @_;
         print("Set-Cookie: ");
         print("$name=$val, expires=$exp, path=$path, domain=$dom");
         print(", $secure") if defined($secure);
         print("\n");
     }

     sub getCookies {
         my(%cookies);
         foreach (split (/; /,$ENV{'HTTP_COOKIE'})){
             my($key) = split(/=/, $_);
             $cookies{$key} = substr($_, index($_, "=")+1);
         }
         return(%cookies);
     }

This program shows that the Web server stores a copy of any cookies that you set into the HTTP_COOKIE environment variable. It only performs one level of parsing. In order to create a really useful getCookies() fuNCtion, you need to split the cookie on the comma character and then again on the equals character.
=========================================================
How to find out if a visitor's Web browser supports cookies? The CGI program below will set a cookie and then redirect the visitor's Web browser back to itself with some additional path information. When the script (during its second invocation) sees the extra path information, it checks for the previously created cookie. If it exists, the visitor's browser has passed the test. Otherwise, the visitor's browser does not support cookies.

     #!/usr/bin/perl -w
     use strict;
     if ($ENV{'QUERY_STRING'} ne 'TESTING') {
         print "HTTP/1.0 302 Moved Temporarily\n";
         print "Set-Cookie: Cookie=Test\n";
         print "Location: $ENV{'SCRIPT_NAME'}?TESTING\n\n";
     }
     else {
         my $supports = "doesn't support";
         if ($ENV{'HTTP_COOKIE'} =~ /Cookie=Test/) { $supports = "supports";}
         print("Content-type: text/html\n\n");
         print("<html><body>Your browser, $ENV{'HTTP_USER_AGENT'}, $supports cookies</body></html>");
     }

Here is how to read/store cookies using CGI.pm:  cookie method:
To retrieve cookie - use cookie method without value parameter
 use CGI;
 $query = new CGI;
 %answers = $query->cookie(-name=>'answers');
 # $query->cookie('answers') will work too!

To set cookie:
$cookie = $q->cookie(-name=>'sessionID',
        -value=>'xyzzy',
        -expires=>'+1h',
        -path=>'/cgi-bin/database',
        -domain=>'.capricorn.org',
        -secure=>1);
print $q->header(-cookie=>$cookie);

Store many values (hash) into a cookie:
$cookie=$q->cookie(-name=>'family information',
          -value=>\%childrens_ages);

Store 2 or more cookies: 
$cookie1 = $query->cookie(-name=>'riddle_name',
      -value=>"The Sphynx's Question");
 $cookie2 = $query->cookie(-name=>'answers',
      -value=>\%answers);
 print $query->header(-cookie=>[$cookie1,$cookie2]);
 

Here is an example on how to deal with cookies from Javascript:

<html><head>
<script Language="JavaScript">

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1) endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
 var arg = name + "=";
 var alen = arg.length;
 var clen = document.cookie.length;
 var i = 0;
 while (i < clen) {
   var j = i + alen;
   if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
   i = document.cookie.indexOf(" ", i) + 1;
   if (i == 0) break;
 }
 return null;
}

function SetCookie (name, value) {
 var argv = SetCookie.arguments;
 var argc = SetCookie.arguments.length;
 var expires = (2 < argc) ? argv[2] : null;
 var path = (3 < argc) ? argv[3] : null;
 var domain = (4 < argc) ? argv[4] : null;
 var secure = (5 < argc) ? argv[5] : false;
 document.cookie = name + "=" + escape (value) +
 ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
 ((path == null) ? "" : ("; path=" + path)) +
 ((domain == null) ? "" : ("; domain=" + domain)) +
 ((secure == true) ? "; secure" : "");
}

function display_count() {
  var expdate = new Date();
  var visit;
  // Set expiration date to a year from now.
  expdate.setTime(expdate.getTime() +  (24 * 60 * 60 * 1000 * 365));
  if(!(visit = GetCookie("visit"))) visit = 0;
  visit++;
  SetCookie("visit", visit, expdate, "/", null, false);
  alert("You have visited this page "+ visit + " times." )
}
</script>
</head>
<body onLoad="display_count()">
...
</body>
</html>
======================================================
Using Cookies from Java Servlets:

A Cookie is created by calling the Cookie constructor (below),
which takes two strings: the cookie name and the cookie value.
Neither the name nor the value should contain whitespace or any of:
  [ ] ( ) = , " / ? @ : ;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;

// set cookie example

  Cookie userCookie = new Cookie("user", "uid1234");
  response.addCookie(userCookie);

// read cookies example

  out.println("Cookies:");
  Cookie[] cookies = request.getCookies();
  for (int i = 0; i < cookies.length; i++) {
    String name = cookies[i].getName();
    String value = cookies[i].getValue();
    out.println("  " + name + " : " + value);
======================================================
You can find more information about cookies at these Web sites:
 - do search for cookielib on search engines -
 - http://www.zdnet.com/devhead/resources/scriptlibrary/javascript/cookies.html -
 - http://www.hidaho.com/cookies/cookie.txt -
 - http://www.cookiecentral.com/ -
 - http://www.worldwidemart.com/scripts/cookielib.shtml -
 - http://home.netscape.com/newsref/std/cookie_spec.html -
 - http://www.netscapeworld.com/netscapeworld/nw-07-1996/nw-07-cookies.html -