Setting and Getting Cookies

They have: 850 posts

Joined: Jul 1999

I want to learn how to Set and Receive cookies using Perl. Can someone possibly give me an example of doing this?

Thanks

------------------
A cow produces about 65 pounds of crap a day.

They have: 568 posts

Joined: Nov 1999

I think I can do that.

code:

print "Set-Cookie: name=1:3:6:72:23:25:65:23432:324324; expires=Monday, 12-Dec-2000 00:00:00 GMT; path=/DIR; domain=DOMAIN_NAME;";
print "Content-type: text/html\n\n";
[/code]

DIR is where you put the dir of your web site on the server (http not absoulate path). DOMAIN_NAME is where you put the domain of your server. For instance, if your address was www.linux.com/cookies 
then DIR would be /cookies and DOMAIN_NAME would be www.linux.com  or linux.com. Never put the print "Content-type: text/html\n\n"; before the set cookie line or it will print out the cookie. 

Now to read the cookie.

code:
#!/usr/bin/perl
print "Content-type: text/html\n\n";

sub getCookies {
	local(@rawCookies) = split (/; /,$ENV{'HTTP_COOKIE'});
	local(%cookies);

	foreach(@rawCookies){
	    ($key, $val) = split (/=/,$_);
	    $cookies{$key} = $val;
	} 

	return %cookies; 
} 

%cookies = &getCookies;
[/code];

if you've ever seen a sub routine for processing forms this looks very familiar. To read the cookies you just type print "$cookies{'COOKIE_NAME'}\n";

Hope that clears it up for you. 

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.