Link to home
Start Free TrialLog in
Avatar of schworak
schworak

asked on

Setting and Getting cookies

Is there a way in PERL to set and get the values of cookies? If so, how? A sample would be nice. Thanks!
ASKER CERTIFIED SOLUTION
Avatar of flivauda
flivauda

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of schworak
schworak

ASKER

Thanks! That got me on the right track.... Here is what I came up with from what you gave me. Works great too! If you care to see it in action it is at http://www.g-world.com/my-cgi/myframes.pl?config=1

sub setCookie
{
    local ($key,$value,$keepdays) = @_;

    $cookie = "$key=$value";
    $expiration = &getCookieTimestamp($keepdays);
    print "<meta HTTP-EQUIV='Set-Cookie' CONTENT='$cookie;expires=$expiration'>\n";
}

sub getCookie
{
    local ($findkey) = @_;
    local (@key_val_pairs, $pair, $key, $value, $keepvalue);

    $keepvalue='';
    @key_val_pairs = split(/\;\s*/,$ENV{'HTTP_COOKIE'});
    foreach $pair (@key_val_pairs)
    {
        ($key, $value) = split(/=/,$pair);
        if ($key =~ /\A$findkey\Z/i)
        {
            $keepvalue = $value;
        }
    }
    return $keepvalue;
}

sub getCookieTimestamp
{
    local ( $keepdays) = @_;
    local ($months, $weekdays, $ampm, $time_string, $cookietimeout);

    $cookietimeout = 60 * 60 * 24 * $keepdays;

    local ($sec, $min, $hour, $day, $nmonth, $year, $wday, $yday, $isdst)  = gmtime(time+$cookietimeout);

    $months = "Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec";
    $weekdays = "Sun/Mon/Tue/Wed/Thu/Fri/Sat";

    if ($hour > 12)
    {
        $hour -= 12; $ampm = "pm";
    }
    else
    {
        $ampm = "am";
    }
    if ($hour == 0) { $hour = 12; }
    $year += 1900;
    $week  = (split("/", $weekdays))[$wday];
    $month = (split("/", $months))[$nmonth];

    $time_string = sprintf("%s, %s %s %s %02d:%02d:%02d GMT", $week, $day, $month, $year, $hour, $min,    $sec);
    return $time_string;
}