Apr 13, 2008

Using Cookies in Perl, Perl Cookies

Perl Cookies

Cookies are used to maintain state information between the web server and the client browser. For example, if the client filled out a survey, rather than displaying the survey form the next time they view, the results of the survey may be displayed:

Setting a cookie

The below sets a cookie to expire in 1 year. It sets a cookie name of "ospoll" and a value of "done" to indicate an operating system poll was taken by the client.

#!/usr/local/bin/perl
# Place a cookie on the user's machine to show the poll was taken.
$fut_time=gmtime(time()+365*24*3600)." GMT";  # Add 12 months (365 days)
$cookie = "ospoll=done; path=/; expires=$fut_time; $secure";
print "Set-Cookie: " . $cookie . "\n";

Using CGI.pm

#!/usr/local/bin/perl
 
use CGI;
$cgiCkie = new CGI;
$fut_time=gmtime(time()+365*24*3600)." GMT";  # Add 12 months (365 days)
 
$cookie = $cgiCkie->cookie(-name=>‘ospoll’,
               -value=>‘done’,
               -expires=>$fut_time,
               -path=>‘/’);
print $cgiCkie->header(-cookie=>$cookie);

Getting a Cookie

The following example reads the cookies into the string value $recvd_cookies. Then it splits each cookie into an array of strings with the line:

@cookies = split /;/, $rcvd_cookies;

Then it checks each cookie in the array to see if a cookie name of "ospoll" with the value of "done" or "start" exists and sets appropriate flags.

#!/usr/local/bin/perl
 
#Check to see if a cookie with the name ospoll1 and value done or start are on the client
$rcvd_cookies = $ENV{'HTTP_COOKIE'};
@cookies = split /;/, $rcvd_cookies;
foreach $cookie (@cookies)
{
   if ($cookie eq "ospoll1=done")
   { 
      $polltaken=1; #Poll was previously taken
   }
   if ($cookie eq "ospoll1=start")
   {
       $pollready=1;
   }
}

No comments:

Post a Comment

Popular Posts