Search code examples
perlcookiescgisend

Passing multiple values in perl cookie


I know how to pass one value (variable) in the cookie, but how do I send multiple values in one cookie. Here is how I did my cookie

Sending:

my $name = $query->param('name');
print "Set-Cookie:name=$name\n";

Reading:

$name = cookie('name');

Now I have other variables such as height, weight etc.. How do I do this?

Thanks in advance


Solution

  • There may be better ways, but this is a cheap and easy one that comes to mind:

    use MIME::Base64;  # for encode_base64 / decode_base64
    use YAML::XS;      # for Dump and Load
    
    # Setting the cookie:
    #  -- Put the keys you want to store in a hash  
    #  -- encode as follows:
    my $cookie_value = encode_base64( Dump( \%hash ) );
    
    print "Set-Cookie:monster=$cookie_value\n";
    
    
    # To decode the cookie:
    #  -- Get the cookie value into a string
    #  -- Decode into a hashref as follows:
    my $cookie_hash = Load( decode_base64( $cookie_value ) );
    

    That would let you put as much as you want in the cookie, up to whatever the maximum cookie length is.

    You can find those modules at cpan.org: