home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Practical mod_perlPractical mod_perlSearch this book

A.5. Handling Cookies

Unless you use a module such as CGI::Cookie or Apache::Cookie, you need to handle cookies yourself. Cookies are accessed via the $ENV{HTTP_COOKIE} environment variable. You can print the raw cookie string as $ENV{HTTP_COOKIE}. Here is a fairly well-known bit of code to take cookie values and put them into a hash:

sub get_cookies {
    # cookies are separated by a semicolon and a space, this will
    # split them and return a hash of cookies
    my @rawCookies = split /; /, $ENV{'HTTP_COOKIE'};
    my %cookies;

    foreach (@rawCookies){
        my($key, $val) = split /=/, $_;
        $cookies{$key} = $val;
    }

    return %cookies;
}

And here's a slimmer version:

sub get_cookies {
    map { split /=/, $_, 2 } split /; /, $ENV{'HTTP_COOKIE'};
}


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.