CGI::Si...::Cookie(3)

okay bestie, welcome to the User Contributed Perl Documentation page for CGI::Si...::Cookie(3) β€” aka CGI::Simple::Cookie, and it’s giving literal HTTP cookie royalty. πŸͺπŸ‘‘ iconic behavior only.

πŸ’– NAME πŸ’–

CGI::Simple::Cookie β€” Interface to HTTP cookies. That’s the whole name, no cap. ✨

✨ SYNOPSIS ✨

use CGI::Simple::Standard qw(header);
use CGI::Simple::Cookie;

# Create new cookies and send them
$cookie1 = CGI::Simple::Cookie->new( -name=>'ID', -value=>123456 );
$cookie2 = CGI::Simple::Cookie->new( -name=>'preferences',
                                    -value=>{ font => Helvetica,
                                              size => 12 }
                                  );
print header( -cookie=>[$cookie1,$cookie2] );

# fetch existing cookies
%cookies = CGI::Simple::Cookie->fetch;
$id = $cookies{'ID'}->value;

# create cookies returned from an external source
%cookies = CGI::Simple::Cookie->parse($ENV{COOKIE});

πŸŽ€ DESCRIPTION πŸŽ€

CGI::Simple::Cookie is an interface to HTTP/1.1 cookies, bestie β€” that’s the mechanism that lets Web servers store persistent information on the browser’s side of the connection. Even though CGI::Simple::Cookie is intended to be used with CGI::Simple (and is literally used by it internally), you can absolutely use this module independently. πŸ’…

For full information on cookies see:

http://tools.ietf.org/html/rfc2109
http://tools.ietf.org/html/rfc2965
https://dcthetall.github.io/CHIPS-spec/draft-cutler-httpbis-partitioned-cookies.html

CGI::Simple::Cookie is object oriented. Each cookie object has a name and a value. The name is any scalar value. The value is any scalar or array value (associative arrays are also allowed). Cookies also have several optional attributes, including:

  1. expiration date β€” this tells the browser how long to hang on to the cookie. If the cookie specifies an expiration date in the future, the browser will store the cookie information in a disk file and return it to the server every time the user reconnects (until the expiration date is reached). If the cookie specifies an expiration date in the past, the browser will remove the cookie from the disk file. If the expiration date is not specified, the cookie will persist only until the user quits the browser.
  2. domain β€” this is a partial or complete domain name for which the cookie is valid. The browser will return the cookie to any host that matches the partial domain name. For example, if you specify a domain name of ".capricorn.com", then the browser will return the cookie to web servers running on any of the machines "www.capricorn.com", "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names must contain at least two periods to prevent attempts to match on top level domains like ".edu". If no domain is specified, then the browser will only return the cookie to servers on the host the cookie originated from.
  3. path β€” if you provide a cookie path attribute, the browser will check it against your script’s URL before returning the cookie. For example, if you specify the path "/cgi-bin", then the cookie will be returned to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl", but not to the script "/cgi-private/site_admin.pl". By default, the path is set to "/", so that all scripts at your site will receive the cookie. 🫢
  4. secure flag β€” if the "secure" attribute is set, the cookie will only be sent to your script if the CGI request is occurring on a secure channel, such as SSL.
  5. HttpOnly flag β€” if the "httponly" attribute is set, the cookie will only be accessible through HTTP Requests. This cookie will be inaccessible via JavaScript (to prevent XSS attacks). See this URL for more information including supported browsers:
http://www.owasp.org/index.php/HTTPOnly
  1. samesite flag β€” allowed settings are "Strict", "Lax" and "None". As of April 2018, support is limited mostly to recent releases of Chrome and Opera. More deets here:
https://tools.ietf.org/html/draft-west-first-party-cookies-07
  1. priority flag β€” this attribute allows servers to specify a retention priority for HTTP cookies that will be respected by user agents during cookie eviction. Allowed settings are "Low", "Medium" and "High".
  2. partitioned flag β€” if the "partitioned" attribute is set, the cookie is restricted to the contexts in which a cookie is available to only those whose top-level document is same-site with the top-level document that initiated the request that created the cookie. πŸ”₯
https://dcthetall.github.io/CHIPS-spec/draft-cutler-httpbis-partitioned-cookies.html

🧚 Creating New Cookies 🧚

$c = CGI::Simple::Cookie->new( -name    =>  'foo',
                               -value    =>  'bar',
                               -expires  =>  '+3M',
                               -max-age  =>  '+3M',
                               -domain   =>  '.capricorn.com',
                               -path     =>  '/cgi-bin/database',
                               -secure   =>  1,
                               -samesite =>  'Lax',
                             );

Create cookies from scratch with the new method. The -name and -value parameters are required. The name must be a scalar value. The value can be a scalar, an array reference, or a hash reference. (At some point in the future cookies will support one of the Perl object serialization protocols for full generality.) πŸ’–

  • -expires β€” accepts any of the relative or absolute date formats recognized by CGI::Simple, for example "+3M" for three months in the future. See CGI::Simple’s documentation for details.
  • -max-age β€” accepts the same data formats as -expires, but sets a relative value instead of an absolute like -expires. This is intended to be more secure since a clock could be changed to fake an absolute time. In practice, as of 2011, "-max-age" still does not enjoy the widespread support that "-expires" has. You can set both, and browsers that support "-max-age" should ignore the "Expires" header. The drawback to this approach is the bit of bandwidth for sending an extra header on each cookie.
  • -domain β€” points to a domain name or to a fully qualified host name. If not specified, the cookie will be returned only to the Web server that created it.
  • -path β€” points to a partial URL on the current server. The cookie will be returned to all URLs beginning with the specified path. If not specified, it defaults to '/', which returns the cookie to all pages at your site.
  • -secure β€” if set to a true value, instructs the browser to return the cookie only when a cryptographic protocol is in use.
  • -httponly β€” if set to a true value, the cookie will not be accessible via JavaScript.
  • -samesite β€” may be "Lax", "Strict" or "None" and is an evolving part of the standards for cookies. Please refer to current documentation regarding it.

Within a CGI script you can send a cookie to the browser by creating one or more Set-Cookie: fields in the HTTP header. Here is a typical sequence:

$c = CGI::Simple::Cookie->new( -name    =>  'foo',
                               -value   =>  ['bar','baz'],
                               -expires =>  '+3M'
                              );

print "Set-Cookie: $c\n";
print "Content-Type: text/html\n\n";

To send more than one cookie, create several Set-Cookie: fields. Alternatively, you may concatenate the cookies together with "; " and send them in one field.

If you are using CGI::Simple, you send cookies by providing a -cookie argument to the header() method:

print header( -cookie=>$c );

Mod_perl users can set cookies using the request object’s header_out() method:

$r->header_out('Set-Cookie',$c);

Internally, Cookie overloads the "" operator to call its as_string() method when incorporated into the HTTP header. as_string() turns the Cookie’s internal representation into an RFC-compliant text representation. You may call as_string() yourself if you prefer:

print "Set-Cookie: ",$c->as_string,"\n";

πŸ’œ Recovering Previous Cookies πŸ’œ

%cookies = CGI::Simple::Cookie->fetch;

fetch returns an associative array consisting of all cookies returned by the browser. The keys of the array are the cookie names. You can iterate through the cookies this way:

%cookies = CGI::Simple::Cookie->fetch;
foreach (keys %cookies) {
    do_something($cookies{$_});
}

In a scalar context, fetch() returns a hash reference, which may be more efficient if you are manipulating multiple cookies.

CGI::Simple uses the URL escaping methods to save and restore reserved characters in its cookies. If you are trying to retrieve a cookie set by a foreign server, this escaping method may trip you up. Use raw_fetch() instead, which has the same semantics as fetch(), but performs no unescaping.

You may also retrieve cookies that were stored in some external form using the parse() class method:

$COOKIES = `cat /usr/tmp/Cookie_stash`;
%cookies = CGI::Simple::Cookie->parse($COOKIES);

πŸ‘‘ Manipulating Cookies πŸ‘‘

Cookie objects have a series of accessor methods to get and set cookie attributes. Each accessor has a similar syntax. Called without arguments, the accessor returns the current value of the attribute. Called with an argument, the accessor changes the attribute and returns its new value. Slay. ✨

πŸ’… name()

Get or set the cookie’s name. Example:

$name = $c->name;
$new_name = $c->name('fred');

πŸ’… value()

Get or set the cookie’s value. Example:

$value = $c->value;
@new_value = $c->value(['a','b','c','d']);

value() is context sensitive. In a list context it will return the current value of the cookie as an array. In a scalar context it will return the first value of a multivalued cookie.

πŸ’… domain()

Get or set the cookie’s domain.

πŸ’… path()

Get or set the cookie’s path.

πŸ’… expires()

Get or set the cookie’s expiration time.

πŸ’… max_age()

Get or set the cookie’s maximum age.

πŸ’… secure()

Get or set the cookie’s secure flag.

πŸ’… httponly()

Get or set the cookie’s HttpOnly flag.

πŸ’… samesite()

Get or set the cookie’s samesite value.

πŸ’… priority()

Get or set the cookie’s priority value.

πŸ’… partitioned()

Get or set the cookies partitioned flag. 🫢

πŸ’– AUTHOR INFORMATION πŸ’–

okay so credit where credit is due, bestie β€” the original version copyright is 1997-1998, Lincoln D. Stein. All rights reserved. Then it was originally copyright 2001 Dr James Freeman <jfreeman@tassie.net.au>, and this release is by Andy Armstrong <andy@hexten.net>. iconic lineage honestly πŸ‘‘

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. periodt ✨

Address bug reports and comments to: andy@hexten.net β€” like, if you gotta report a bug or drop a comment, that's the inbox 🫢


πŸ’€ BUGS πŸ’€

This section intentionally left blank :-)

no cap, that's literally what it says. the bugs section is giving minimalist main character energy πŸ™ˆβœ¨


🌈 SEE ALSO 🌈

  • CGI::Carp
  • CGI::Simple

go read those too, iykyk πŸ¦‹


that's the whole page, bestie πŸ’– β€” this footer energy is perl v5.42.0, dated 2025-12-02, and the page is CGI::Si...::Cookie(3). byeee πŸŽ€

πŸ“¦ where this page comes from