Lesson 12 | Clearing cookies |
Objective | Identify the steps involved in clearing a cookie |
my
) instead of global variables, which is a better practice for avoiding unwanted side effects.CRLF
, you can use \n
, which is more readable.each
loop can be avoided by using more modern techniques for hash iteration.CGI
module can handle query strings and cookies more elegantly. This avoids manually parsing the query string and cookie headers.open my $fh
) instead of global filehandles.#!/usr/bin/perl use strict; use warnings; use CGI; use CGI::Cookie; # Create a new CGI object my $cgi = CGI->new; # Get server information my $servername = $cgi->server_name(); my $scriptname = $cgi->script_name(); my $callback = "http://$servername$scriptname"; # Expired date for clearing cookies my $expdate = "Mon, 01-Jan-1990 00:00:00 GMT"; # Get query parameters my %query = $cgi->Vars(); my $state = $query{'state'} // 'first'; # Default to 'first' state # Parse cookies my %cookies = CGI::Cookie->fetch; my $cookie_value = $cookies{'cookie_name'} ? $cookies{'cookie_name'}->value : undef; # Print HTTP header print $cgi->header(-type => 'text/html'); # Main logic if ($state eq 'first') { first(); } elsif ($state eq 'setcookie') { setcookie(); } else { unknown(); } exit;
# STATE SCREENS sub first { print $cgi->start_html("First State"); print "Key Changes:You are in the first state. Current cookie: " . ($cookie_value // 'No cookie') . "
"; print $cgi->end_html; } sub setcookie { if ($cgi->param('cookie') && $cgi->param('value')) { my $cookie = CGI::Cookie->new( -name => 'cookie_name', -value => $cgi->param('value'), -expires => '+1h' # Set cookie to expire in 1 hour ); print $cgi->header(-cookie => $cookie); print "Cookie set with value: " . $cgi->param('value') . "
"; } else { print "Cookie not set
"; } } sub unknown { print $cgi->start_html("Unknown State"); print "Unknown state encountered.
"; print $cgi->end_html; }
my
) variables to avoid unintended global scope.CGI::Cookie
makes setting and clearing cookies easier and more readable.CGI->header
method handles headers more robustly.