Perl CGI  «Prev  Next»

Lesson 12Clearing cookies
ObjectiveIdentify the steps involved in clearing a cookie

Clearing Cookies in Perl


Simple Perl Cookie example

This Perl code can be used to clear cookies by setting the `expires` attribute of the cookie to a date in the past, which tells the browser to delete the cookie. The following code is functional but could benefit from both simplification and modernization. Here's a breakdown of areas that can be improved:
  1. Simplification:
    • Global Variables: Perl allows using lexical variables (my) instead of global variables, which is a better practice for avoiding unwanted side effects.
    • Removing `CRLF`: Instead of manually defining CRLF, you can use \n, which is more readable.
    • Hardcoding Date: A hardcoded expiration date for cookies can be made more flexible by using Perl’s date handling modules.
    • `each` Loop: The each loop can be avoided by using more modern techniques for hash iteration.
  2. Modernization:
    • Use of `strict` and `warnings`: It's common practice to include these pragmas in modern Perl to catch common mistakes and encourage better coding habits.
    • CGI Module: Perl’s CGI module can handle query strings and cookies more elegantly. This avoids manually parsing the query string and cookie headers.
    • Lexical Filehandles: Modern Perl uses lexical filehandles (i.e., open my $fh) instead of global filehandles.
    • Template::Toolkit or Other Templating Modules: Instead of embedding Perl code directly into HTML, you could use templating engines to separate concerns better.

Revised Code with Improvements:
#!/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 "

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; }
Key Changes:
  1. Use of `CGI` module: This module simplifies the handling of query parameters, headers, and cookies. It removes the need to manually parse query strings and cookies.
  2. Lexical variables: Replaced global variables with lexical (my) variables to avoid unintended global scope.
  3. Simplified cookie handling: Using CGI::Cookie makes setting and clearing cookies easier and more readable.
  4. Better filehandle usage: Replaced old-style filehandles with modern lexical filehandles.
  5. Removed hardcoded headers: The CGI->header method handles headers more robustly.
This version is more maintainable, readable, and secure, while making use of modern Perl practices.

ClearPerl - Cookie - Exercise


SEMrush Software