networking intermediate

How to implement HTTP cookie handling in Perl?

Question

How to implement HTTP cookie handling in Perl?

Handling HTTP cookies in Perl is a common task in web programming, especially when managing sessions, user preferences, or tracking. Cookies are sent by the server to the client in HTTP response headers and then returned by the client in subsequent requests.

To implement cookie handling in Perl, you typically need to:

  • Set cookies by sending appropriate Set-Cookie headers to the client
  • Read cookies sent by the client via the Cookie HTTP header

Using Core Perl Modules

The core module CGI (part of Perl’s standard distribution) offers straightforward methods to manage cookies. In CGI scripts, you can use the CGI::Cookie package to create, parse, and read cookies.

Basic Workflow with CGI::Cookie

  • Create a cookie object with name, value, expiration, etc.
  • Print a HTTP header with the Set-Cookie directive
  • Read incoming cookies from the HTTP_COOKIE environment variable

Example: Setting and Reading Cookies


#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use CGI::Cookie;

# Create a new CGI object
my $cgi = CGI->new;

# Create a cookie (e.g., set a cookie named 'user' with value 'Alice')
my $cookie = CGI::Cookie->new(
    -name    => 'user',
    -value   => 'Alice',
    -expires => '+1h',        # expires in 1 hour
    -path    => '/',          # scope for the cookie
);

# Get all incoming cookies sent by the client
my %cookies = CGI::Cookie->fetch;

# Retrieve the value of cookie named 'user', if set
my $user = exists $cookies{'user'} ? $cookies{'user'}->value : 'Guest';

# Print the HTTP header including the Set-Cookie header
print $cgi->header(
    -type    => 'text/html',
    -cookie  => $cookie,
);

# Print response body
print <<"HTML";

Cookie Example

Hello, $user!

A cookie named user has been set with value 'Alice'

Reload the page to see the cookie being sent back.

HTML

Explanation of the Code

  • CGI->new creates a CGI object to handle HTTP request/response.
  • CGI::Cookie->new creates a cookie with desired attributes. The -expires option accepts relative times like +1h (1 hour), +1d (1 day), etc.
  • CGI::Cookie->fetch parses the incoming Cookie HTTP header and returns a hash of cookie objects keyed by cookie name.
  • The cookie is sent to the client by including it in the HTTP header via header(-cookie => $cookie).
  • The script then prints a simple HTML page showing the cookie value or “Guest” if no cookie is sent.

Important Perl Concepts

  • Sigils: $ for scalars, @ for arrays, and % for hashes. Here, %cookies stores cookie objects keyed by name.
  • Context: Calling CGI::Cookie->fetch in scalar or list context affects its output; here we want all cookies as a hash, so list context is used.
  • TMTOWTDI ("There's more than one way to do it"): You can parse raw environment variables manually, use CGI::Simple, or modern frameworks like Mojolicious or Dancer for more advanced cookie management.

Common Pitfalls

  • Cookies set via HTTP headers are only stored by the browser after the response; they aren’t available from the client until the next request.
  • Always specify the -path and -expires parameters to control cookie scope and lifecycle properly.
  • Beware of cookie size limits (~4KB per cookie) and total cookies per domain limits enforced by browsers.
  • When handling multiple cookies, remember the Cookie header string may contain many cookies separated by semicolons.

For more advanced needs, like signed cookies or secure cookies over HTTPS, consider CPAN modules such as HTTP::Cookies, Mojolicious::Cookie, or server frameworks with built-in session management.

In summary, CGI::Cookie provides a simple and effective core Perl way to implement HTTP cookie handling, suitable for most intermediate scripting tasks.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 36ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Set-Cookie: user=Alice; path=/; expires=Tue, 30-Dec-2025 07:29:32 GMT
Date: Tue, 30 Dec 2025 06:29:32 GMT
Content-Type: text/html; charset=ISO-8859-1

<html>
<head><title>Cookie Example</title></head>
<body>
<p>Hello, <b>Guest</b>!</p>
<p>A cookie named <code>user</code> has been set with value 'Alice'</p>
<p>Reload the page to see the cookie being sent back.</p>
</body>
</html>
STDERR
(empty)

Was this helpful?

Related Questions