views:

404

answers:

5

I'd like to store some data in a cookie and my initial though was to pack it myself, but then I remembered that There Is A Module for Everything.

I have looked at both Storable and FreezeThaw. Both seem appropriate, though the latter mentions string specifically and seems to serialize into a string without newlines, whereas Storable creates a string that contains newlines.

Which module is best for my application, or is there something even more appropriate?

+4  A: 

It's generally not a great idea to store large chunks of data in client-side cookies, both for security and compatibility reasons. Instead, I would recommend using something like CGI::Session, which will give you automatic session cookies, and you can store the data in a table or file on the server-side. Then it doesn't matter what serialization method you use.

friedo
I'm not planning to store any significant data, just a couple of IDs.
Drew Stephens
Keep client state on client, keep server state on server. It is best practice recommended even REST design.
Hynek -Pichi- Vychodil
+2  A: 

Both Storable and FreezeThaw can produce non-printable or other problematic characters, as well as newlines. But most modules that will generate and parse cookie headers for you will automatically encode any characters that need it, so you shouldn't need to worry about it.

But I'd second the recommendation to store more complex data server-side.

ysth
+3  A: 

If storing the data in a cookie is really what you want to do, and sessions aren't appropriate, I would go with Storable plus MIME::Base64 to make the data cookie-safe. Possibly with the addition of Digest::HMAC for tamper-resistance and/or Crypt::Rijndael to make the data totally opaque to the user, as appropriate.

hobbs
+2  A: 

I ended up using Storable and encrypting the result before putting it into a cookie:

use CGI::Cookie;
use Storable qw(freeze);
use Crypt::CBC;

my $data = {
    'ID'  => 7,
    'foo' => 'bar',
};

my $cipher = Crypt::CBC->new(
    -cipher => 'Rijndael',
    -header => 'none',
    -key    => $key,
    -iv     => $iv,
);

my $enc = $cipher->encrypt_hex(freeze($data));
my $cookie = CGI::Cookie->new(
    -name   => 'oatmeal',
    -value  => $enc,
);
Drew Stephens
+3  A: 

Don't store real data in cookies. Store some identifier that allows you to look up the cookie data on the server side. So, don't use either module. :)

brian d foy