HANDLING COOKIES





HANDLING COOKIES

In Perl the CGI::Cookie module will create a cookie HTTP header for you by supplying the cookie data, domain, and expiry date to a new cookie object. For example

my $query = new CGI;
my $cookietext = $query->cookie(-name => 'sample',
                               -value => { login =>
                                           $login,
                                           other =>
                                          'Other'
                               -path => '/',
                               -domain =>
                                   'mcwords.mchome.com',
                               -expires => '+1y');
print "Set-Cookie: $cookietext\n";

In Python there is a third party module called Cookie which will build a new cookie for you. For example, we could rewrite the above using the Cookie module like this:

import Cookie
cookie = Cookie.SmartCookie()
cookie['sample'] = 'login=%s; other=Other' % (login)
cookie['sample']['path'] = '/'
cookie['sample']['domain'] = 'mcwords.mchome.com'
cookie['sample']['expires'] = 365*24*3600
print cookie

Note that we have to actually calculate the future value ourselves (in seconds) rather than using relative strings.

To actually parse a cookie you need to use the load() method on a SmartCookie object to load the information supplied in the HTTP_COOKIE environment variable:

import Cookie, os

cookie = Cookie.SmartCookie()
cookie.load(os.environ['HTTP_COOKIE'])
print cookie['sample']

     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows