March 1, 2021
Hot Topics:

Tracking Users Using WML

  • By Steve Schafer
  • Send Email »
  • More Articles »
Reading Cookies with Perl

Reading cookies with Perl is even easier than setting them, thanks to the environment variable HTTP_COOKIE. This variable contains name/value pairs for all applicable cookies (those matching the current scope).

To parse the name/value list, you could use the following code:

@nvpairs=split(/[,;] */, $ENV{'HTTP_COOKIE'});foreach $pair (@nvpairs) {   ($name, $value) = split(/=/, $pair);   $cookie{$name} = $value;}

This code effectively parses the cookie list into the array $cookie, where each value can be accessed by its name. For example, our earlier "name" example would yield:

$cookie{'name'} = "Steve"

An extended example, displaying the cookie value in WML, is shown below:

#!/usr/bin/perl# Break cookies into name/value pairs# and store into cookie array@nvpairs=split(/[,;] */, $ENV{'HTTP_COOKIE'});foreach $pair (@nvpairs) {   ($name, $value) = split(/=/, $pair);   $cookie{$name} = $value;}# Define WML deck$deck = '<wml>  <card>    <p>      Cookie (name) = '.$cookie{'name'}.'    </p>  </card></wml>';# Send Content-type and Set-Cookie headersprint "Content-type: text/vnd.wap.wml \n";print "Set-Cookie: name=Steve; expires=$date; \n";# Send WML headersprint "\n<?xml version=\"1.0\"?>\n";print "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\""   . " \"http://www.wapforum.org/DTD/wml_1.1.xml\">\n";# Send the deckprint $deck;

If the cookie was still set, this code would display the following:

Cookie (name) = Steve
Deleting Cookies

To remove a cookie, you simply set the expiration of the cookie to a date/time that has already passed. For example, we could use the code earlier but subtract a day or two to expire the cookie. The code, using Date::Calc functions, would resemble the following:

# Get today in GMT($year,$month,$day) = Today([$gmt]);# Subtract a year (365 days)($year,$month,$day) =  Add_Delta_Days($year,$month,$day,"-365");# Get textual representations of month and day of week$dow =  Day_of_Week_to_Text(Day_of_Week($year,$month,$day));$month = Month_to_Text($month);# Make sure day is two digitsif ($day<10){ $day = '0'.$day;}# Assemble expiration date$date = $dow.", ".$day."-".$month."-".$year." 23:59:59 GMT";

Note the use of a minus sign in the Add_Delta_Days function to subtract a year from today. We could just as easily subtract only one day.

Page 4 of 5

This article was originally published on March 27, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date