Lesson 10 | Setting and reading cookies |
Objective | Learn how to set and read cookies. |
Setting and Reading Cookies
To send a cookie from a CGI program, simply send the Set-cookie header sometime before the end of your headers, like this:
$crlf = "\x0d\x0a";
$cookiehead = "UserID=007";
print "content-type: text/html$crlf";
print "set-cookie: $cookiehead$crlf";
print "$crlf";
...rest of program
Reading a cookie
To see what cookies are coming back from the client, check the $ENV{HTTP_COOKIE} variable like this:
$cookie = $ENV{HTTP_COOKIE};
print "<p>Here's a cookie: $cookie<br>\n" if $cookie;
It is valuable to keep in mind (especially when you are testing your code!) that you won't see the cookie come back from the browser until the next connection. It takes a whole round-trip (in other words, Connection A: send the cookie to the browser; Connection B: get the cookie from the browser) for the cookie to appear.
Set Perl Cookie - Quiz
Click the quiz link below for another exciting and challenging (and brief) multiple choice quiz on cookies.
Set Perl Cookie - Quiz