Solved

Setting and Getting cookies

Posted on 1998-12-29
2
196 Views
Last Modified: 2010-03-05
Is there a way in PERL to set and get the values of cookies? If so, how? A sample would be nice. Thanks!
0
Comment
Question by:schworak
2 Comments
 
LVL 1

Accepted Solution

by:
flivauda earned 100 total points
Comment Utility
   ==================
    # Here is how you would set the cookies
    &setMemberCookie($username);    # expires in one day
    &setMemberCookie($username, 1); # expires in one year

    # Here is how you would read the cookies
    &getMemberCookie(*COOKIE);


    sub setMemberCookie
    { local ( $username, $permanentcookieflag) = @_;

      $cookie = uname=$username&otherinfo=$otherinfo;
      $expiration = &getCookieTimestamp($permanentcookieflag);
print "Set-Cookie: login=$cookie; expires=$expiration;path=/;domain=.yourdomain.com;\n";
      $ENV{'HTTP_COOKIE'} = "login=$cookie; $ENV{'HTTP_COOKIE'}";
    }


    # getCookieTimestamp
    #
    # returns a timestring in the format:
    # Weekday, DD Month YEAR HH:MM:SS GMT
    #
    # if the call to setMemberCookie contains a permanentcookie
    # flag that is true, then the cookie will expire in one year.
    # otherwise the cookie will expire in one day.
    #
    #############################################################

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

        if ( $permanentcookieflag )
          { $cookietimeout = 60 * 60 * 24 * 365;
          }
        else
          { $cookietimeout = 60 * 60 * 24;
          }

        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;
    }



    # getMemberCookie
    #
    # if the login=blablabla cookie is set, decode it and return
    # the pointer to the hash.  otherwise return false.
    #
    #############################################################

    sub getMemberCookie
    { local (*COOKIE_DATA) = @_;
      local ( $cookie_string, @key_value_pairs, $key_value, $key, $value);

      if ( $ENV{'HTTP_COOKIE'} =~ /login=([^;]+)/ )
      {
      }
      else
      {
        return("false");
      }

      @key_value_pairs = split (/&/, $cookie_string);
      foreach $key_value (@key_value_pairs)
        { ($key, $value) = split (/=/, $key_value);
          $value =~ tr/+/ /;
          $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;

          if (defined($COOKIE_DATA{$key}))
            { $COOKIE_DATA{$key} = join ("\0", $COOKIE_DATA{$key}, $value);
            }
          else
            { $COOKIE_DATA{$key} = $value;
            }
        }

       return %COOKIE_DATA;
    }
0
 
LVL 3

Author Comment

by:schworak
Comment Utility
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;
}




0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now