# Setting and reading cookies with Perl?

**URL:** https://boards.straightdope.com/t/setting-and-reading-cookies-with-perl/56984
**Category:** Factual Questions
**Created:** [March 6, 2001, 7:51pm UTC](https://boards.straightdope.com/t/setting-and-reading-cookies-with-perl/56984 "2001-03-06T19:51:04Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![point\_taken](https://avatars.discourse-cdn.com/v4/letter/p/5f8ce5/32.png) [@point\_taken](https://boards.straightdope.com/u/point_taken)
#### Post date: [March 6, 2001, 7:51pm UTC](https://boards.straightdope.com/t/setting-and-reading-cookies-with-perl/56984/1 "2001-03-06T19:51:04Z")

</div>

I’m having trouble setting and reading cookies with a Perl script. I was wondering if anyone has a “generic” perl script that will help me accomplish my goal.

Thanks

---

<div class="post-metadata">

### Author: ![CurtC](https://avatars.discourse-cdn.com/v4/letter/c/ce73a5/32.png) [@CurtC](https://boards.straightdope.com/u/CurtC)
#### Post date: [March 6, 2001, 10:24pm UTC](https://boards.straightdope.com/t/setting-and-reading-cookies-with-perl/56984/2 "2001-03-06T22:24:29Z")

</div>

Here’s what I use. To set a cookie, call the SetCookie sub right after you print the “Content type” line, before the blank line followed by HTML (IOW, in the header).

* * *

use strict;

my $Cookie\_Exp\_Date = ‘’;

# Should be defined as: Wdy, DD-Mon-YYYY HH:MM:SS GMT

my $Cookie\_Path = ‘’;  
my $Cookie\_Domain = ‘’;  
my $Secure\_Cookie = ‘0’;

my @Cookie\_Encode\_Chars = qw/% + ; , = & :: \s/;  
my %Cookie\_Encode\_Chars = (’%’, ‘%25’,  
‘+’, ‘%2B’,  
‘;’, ‘%3B’,  
‘,’, ‘%2C’,  
‘=’, ‘%3D’,  
‘&’, ‘%26’,  
‘::’, ‘%3A%3A’,  
‘\s’, ‘+’);

my @Cookie\_Decode\_Chars = qw/+ %3A%3A %26 %3D %2C %3B %2B %25/;  
my %Cookie\_Decode\_Chars = (’+’, ’ ',  
‘%3A%3A’, ‘::’,  
‘%26’, ‘&’,  
‘%3D’, ‘=’,  
‘%2C’, ‘,’,  
‘%3B’, ‘;’,  
‘%2B’, ‘+’,  
‘%25’, ‘%’);

my @Weekday = qw/Sun Mon Tue Wed Thu Fri Sat/;  
my @MonthName = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;

sub GetCookies  
{  
my (%Cookies,$cookie,$value,$char);

if ($ENV{‘HTTP\_COOKIE’})  
{  
foreach (split(/; /,$ENV{‘HTTP\_COOKIE’}))  
{  
($cookie,$value) = split(/=/);  
foreach $char (@Cookie\_Decode\_Chars)  
{  
$cookie =~ s/$char/$Cookie\_Decode\_Chars{$char}/g;  
$value =~ s/$char/$Cookie\_Decode\_Chars{$char}/g;  
}  
$Cookies{$cookie} = $value;  
}  
}  
return %Cookies;  
}

sub GetCookieDate  
{

# take time argument, and convert to “Wdy, DD-Mon-YYYY HH:MM:SS GMT”

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,isdst) = gmtime(\_[0]);

$wday = $Weekday[$wday]; # convert number to a string.  
$mon = $MonthName[$mon];

# format times to fill two digits.

if ($hour\<10) { $hour = “0” . $hour }  
if ($min\<10) { $min=“0” . $min }  
if ($sec\<10) { $sec = “0” . $sec}  
if ($mday\<10) { $mday = “0” . $mday }  
$year = $year + 1900;  
return( $wday . “, " . $mday . “-” . $mon . “-” . $year . " " . $hour . “:” . $min . “:” . $sec . " GMT” );  
}

sub SetCookie {

# arguments passed: cookie name, value, exp date, path, domain

# exp date needs to be in Perl’s seconds-since-1970 format

# if exp date is “”, then it expires when browser is closed.

# if path or domain is “”, default is assumed.

my ($cookie,$value,$exp,$path,$domain) = @\_;  
my $char;  
foreach $char (@Cookie\_Encode\_Chars)  
{  
$cookie =~ s/$char/$Cookie\_Encode\_Chars{$char}/g;  
$value =~ s/$char/$Cookie\_Encode\_Chars{$char}/g;  
}  
print 'Set-Cookie: ’ . $cookie . ‘=’ . $value . ‘;’;

```
if ($exp)
  {
  $exp = GetCookieDate($exp);
  print ' expires=' . $exp . ';';
  }

if ($path) { print ' path=' . $path . ';' }

if ($domain) { print ' domain=' . $domain . ';' };

print "

```

## "; }

---

<div class="post-metadata">

### Author: ![Tretiak](https://avatars.discourse-cdn.com/v4/letter/t/a88e57/32.png) [@Tretiak](https://boards.straightdope.com/u/Tretiak)
#### Post date: [March 7, 2001, 3:05am UTC](https://boards.straightdope.com/t/setting-and-reading-cookies-with-perl/56984/3 "2001-03-07T03:05:54Z")

</div>

Have you tried using the CGI.pm? It makes manageing cookies very easy. You just create cookies using the cookie() function with a -name and -value parameters and placing it in the header. then to retireve the cookie all you need is the name. An example:

#/usr/bi/perl  
use CGI;

## Create the cookie

$mycookie = cookie(-name=\>‘sdmbname’, -value=\>‘Tretiak’);  
print header(-cookie=\>$mycookie);

##Read the cookie  
$name = cookie(‘sdmbname’);  
print(‘This cookie code brought to you by $name’);

There are some other things you can do with it, but that is the basics.

---

<div class="post-metadata">

### Author: ![friedo](https://avatars.discourse-cdn.com/v4/letter/f/8edcca/32.png) [@friedo](https://boards.straightdope.com/u/friedo)
#### Post date: [March 7, 2001, 3:19am UTC](https://boards.straightdope.com/t/setting-and-reading-cookies-with-perl/56984/4 "2001-03-07T03:19:54Z")

</div>

I second the reccomendation for using CGI.pm. It makes things _much_ easier. In addition, CGI.pm will take any incoming cookies and stick them in a scalar of the same name without you having to do anything. Example (this is off the top of my head, so it might have errors.)

```auto

my $query = new CGI;
if (!($query->param('foo'))) { # no cookie
	my $cookie = $query->cookie(-name=>'foo', -value=>'Hello!');
	print $query->header(-cookie=>$cookie);
	print "You did not have a cookie, so I gave you one!";
} else {
	print $query->header;
	print "You already have a cookie. The value is: ", $query->param('foo');
}

```
