Recipe 21.3 Accessing Cookie Values

21.3.1 Problem

You want to examine values client sent you in a cookie.

21.3.2 Solution

Use the CPAN module Apache::Cookie to populate a hash of cookie objects derived from the header sent by the client.

use Apache::Cookie;
$ac = Apache::Cookie->new($r);
%all_cookies = $ac->parse( );

Now each element of that hash is an object representing a single cookie:

$one_cookie = $all_cookies{COOKIE_NAME};

Interrogate the object to learn about that cookie's values:

$one_cookie->value( )     $one_cookie->name( )
$one_cookie->domain( )    $one_cookie->path( )
$one_cookie->expires( )   $one_cookie->secure( )

21.3.3 Discussion

To test whether a cookie was sent by the browser, use exists on the hash element:

unless (exists $all_cookies{chocolate}) {
  $r->header_out(Location => "");
  return REDIRECT;

Don't simply test for truth:

unless ($all_cookies{chocolate}) {  # BAD

Valid cookie values include the empty string and 0, both false to Perl. See the Introduction to Chapter 1 for more.

The CGI::Cookie module is a pure Perl substitute for Apache::Cookie. Its strategy for getting a hash of cookies is slightly different from that of Apache::Cookies:

use CGI::Cookie;
%all_cookies = CGI::Cookie->fetch;

This hash of cookies works the same as the one by Apache::Cookie.

21.3.4 See Also

Writing Apache Modules with Perl and C; Recipe 20.14; Recipe 3.7 in mod_perl Developer's Cookbook; the manpage; documentation for the CGI::Cookie and Apache::Cookie modules from CPAN