{
    "mode": "perldoc",
    "parameter": "CGI::Cookie",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/CGI%3A%3ACookie/json",
    "generated": "2026-06-11T02:33:15Z",
    "synopsis": "use CGI qw/:standard/;\nuse CGI::Cookie;\n# Create new cookies and send them\n$cookie1 = CGI::Cookie->new(-name=>'ID',-value=>123456);\n$cookie2 = CGI::Cookie->new(-name=>'preferences',\n-value=>{ font => Helvetica,\nsize => 12 }\n);\nprint header(-cookie=>[$cookie1,$cookie2]);\n# fetch existing cookies\n%cookies = CGI::Cookie->fetch;\n$id = $cookies{'ID'}->value;\n# create cookies returned from an external source\n%cookies = CGI::Cookie->parse($ENV{COOKIE});",
    "sections": {
        "NAME": {
            "content": "CGI::Cookie - Interface to HTTP Cookies\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use CGI qw/:standard/;\nuse CGI::Cookie;\n\n# Create new cookies and send them\n$cookie1 = CGI::Cookie->new(-name=>'ID',-value=>123456);\n$cookie2 = CGI::Cookie->new(-name=>'preferences',\n-value=>{ font => Helvetica,\nsize => 12 }\n);\nprint header(-cookie=>[$cookie1,$cookie2]);\n\n# fetch existing cookies\n%cookies = CGI::Cookie->fetch;\n$id = $cookies{'ID'}->value;\n\n# create cookies returned from an external source\n%cookies = CGI::Cookie->parse($ENV{COOKIE});\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "CGI::Cookie is an interface to HTTP/1.1 cookies, a mechanism that allows Web servers to store\npersistent information on the browser's side of the connection. Although CGI::Cookie is intended\nto be used in conjunction with CGI.pm (and is in fact used by it internally), you can use this\nmodule independently.\n\nFor full information on cookies see\n\nhttps://tools.ietf.org/html/rfc6265\n\nUSING CGI::Cookie\nCGI::Cookie is object oriented. Each cookie object has a name and a value. The name is any\nscalar value. The value is any scalar or array value (associative arrays are also allowed).\nCookies also have several optional attributes, including:\n\n1. expiration date\nThe expiration date tells the browser how long to hang on to the cookie. If the cookie\nspecifies an expiration date in the future, the browser will store the cookie information in\na disk file and return it to the server every time the user reconnects (until the expiration\ndate is reached). If the cookie species an expiration date in the past, the browser will\nremove the cookie from the disk file. If the expiration date is not specified, the cookie\nwill persist only until the user quits the browser.\n\n2. domain\nThis is a partial or complete domain name for which the cookie is valid. The browser will\nreturn the cookie to any host that matches the partial domain name. For example, if you\nspecify a domain name of \".capricorn.com\", then the browser will return the cookie to Web\nservers running on any of the machines \"www.capricorn.com\", \"ftp.capricorn.com\",\n\"feckless.capricorn.com\", etc. Domain names must contain at least two periods to prevent\nattempts to match on top level domains like \".edu\". If no domain is specified, then the\nbrowser will only return the cookie to servers on the host the cookie originated from.\n\n3. path\nIf you provide a cookie path attribute, the browser will check it against your script's URL\nbefore returning the cookie. For example, if you specify the path \"/cgi-bin\", then the\ncookie will be returned to each of the scripts \"/cgi-bin/tally.pl\", \"/cgi-bin/order.pl\", and\n\"/cgi-bin/customerservice/complain.pl\", but not to the script \"/cgi-private/siteadmin.pl\".\nBy default, the path is set to \"/\", so that all scripts at your site will receive the\ncookie.\n\n4. secure flag\nIf the \"secure\" attribute is set, the cookie will only be sent to your script if the CGI\nrequest is occurring on a secure channel, such as SSL.\n\n5. httponly flag\nIf the \"httponly\" attribute is set, the cookie will only be accessible through HTTP\nRequests. This cookie will be inaccessible via JavaScript (to prevent XSS attacks).\n\nThis feature is supported by nearly all modern browsers.\n\nSee these URLs for more information:\n\nhttp://msdn.microsoft.com/en-us/library/ms533046.aspx\nhttp://www.browserscope.org/?category=security&v=top\n\n6. samesite flag\nAllowed settings are \"Strict\", \"Lax\" and \"None\".\n\nAs of June 2016, support is limited to recent releases of Chrome and Opera.\n\n<https://tools.ietf.org/html/draft-west-first-party-cookies-07>\n",
            "subsections": [
                {
                    "name": "Creating New Cookies",
                    "content": "my $c = CGI::Cookie->new(-name    =>  'foo',\n-value   =>  'bar',\n-expires =>  '+3M',\n'-max-age' =>  '+3M',\n-domain  =>  '.capricorn.com',\n-path    =>  '/cgi-bin/database',\n-secure  =>  1,\n-samesite=>  \"Lax\"\n);\n\nCreate cookies from scratch with the new method. The -name and -value parameters are required.\nThe name must be a scalar value. The value can be a scalar, an array reference, or a hash\nreference. (At some point in the future cookies will support one of the Perl object\nserialization protocols for full generality).\n\n-expires accepts any of the relative or absolute date formats recognized by CGI.pm, for example\n\"+3M\" for three months in the future. See CGI.pm's documentation for details.\n\n-max-age accepts the same data formats as -expires, but sets a relative value instead of an\nabsolute like -expires. This is intended to be more secure since a clock could be changed to\nfake an absolute time. In practice, as of 2011, \"-max-age\" still does not enjoy the widespread\nsupport that \"-expires\" has. You can set both, and browsers that support \"-max-age\" should\nignore the \"Expires\" header. The drawback to this approach is the bit of bandwidth for sending\nan extra header on each cookie.\n\n-domain points to a domain name or to a fully qualified host name. If not specified, the cookie\nwill be returned only to the Web server that created it.\n\n-path points to a partial URL on the current server. The cookie will be returned to all URLs\nbeginning with the specified path. If not specified, it defaults to '/', which returns the\ncookie to all pages at your site.\n\n-secure if set to a true value instructs the browser to return the cookie only when a\ncryptographic protocol is in use.\n\n-httponly if set to a true value, the cookie will not be accessible via JavaScript.\n\n-samesite may be \"Lax\", \"Strict\", or \"None\" and is an evolving part of the standards for\ncookies. Please refer to current documentation regarding it.\n\nFor compatibility with Apache::Cookie, you may optionally pass in a modperl request object as\nthe first argument to \"new()\". It will simply be ignored:\n\nmy $c = CGI::Cookie->new($r,\n-name    =>  'foo',\n-value   =>  ['bar','baz']);\n"
                },
                {
                    "name": "Sending the Cookie to the Browser",
                    "content": "The simplest way to send a cookie to the browser is by calling the bake() method:\n\n$c->bake;\n\nThis will print the Set-Cookie HTTP header to STDOUT using CGI.pm. CGI.pm will be loaded for\nthis purpose if it is not already. Otherwise CGI.pm is not required or used by this module.\n\nUnder modperl, pass in an Apache request object:\n\n$c->bake($r);\n\nIf you want to set the cookie yourself, Within a CGI script you can send a cookie to the browser\nby creating one or more Set-Cookie: fields in the HTTP header. Here is a typical sequence:\n\nmy $c = CGI::Cookie->new(-name    =>  'foo',\n-value   =>  ['bar','baz'],\n-expires =>  '+3M');\n\nprint \"Set-Cookie: $c\\n\";\nprint \"Content-Type: text/html\\n\\n\";\n\nTo send more than one cookie, create several Set-Cookie: fields.\n\nIf you are using CGI.pm, you send cookies by providing a -cookie argument to the header()\nmethod:\n\nprint header(-cookie=>$c);\n\nModperl users can set cookies using the request object's headerout() method:\n\n$r->errheadersout->add('Set-Cookie' => $c);\n\nInternally, Cookie overloads the \"\" operator to call its asstring() method when incorporated\ninto the HTTP header. asstring() turns the Cookie's internal representation into an\nRFC-compliant text representation. You may call asstring() yourself if you prefer:\n\nprint \"Set-Cookie: \",$c->asstring,\"\\n\";\n"
                },
                {
                    "name": "Recovering Previous Cookies",
                    "content": "%cookies = CGI::Cookie->fetch;\n\nfetch returns an associative array consisting of all cookies returned by the browser. The keys\nof the array are the cookie names. You can iterate through the cookies this way:\n\n%cookies = CGI::Cookie->fetch;\nfor (keys %cookies) {\ndosomething($cookies{$});\n}\n\nIn a scalar context, fetch() returns a hash reference, which may be more efficient if you are\nmanipulating multiple cookies.\n\nCGI.pm uses the URL escaping methods to save and restore reserved characters in its cookies. If\nyou are trying to retrieve a cookie set by a foreign server, this escaping method may trip you\nup. Use rawfetch() instead, which has the same semantics as fetch(), but performs no\nunescaping.\n\nYou may also retrieve cookies that were stored in some external form using the parse() class\nmethod:\n\n$COOKIES = `cat /usr/tmp/Cookiestash`;\n%cookies = CGI::Cookie->parse($COOKIES);\n\nIf you are in a modperl environment, you can save some overhead by passing the request object\nto fetch() like this:\n\nCGI::Cookie->fetch($r);\n\nIf the value passed to parse() is undefined, an empty array will returned in list context, and\nan empty hashref will be returned in scalar context.\n"
                },
                {
                    "name": "Manipulating Cookies",
                    "content": "Cookie objects have a series of accessor methods to get and set cookie attributes. Each accessor\nhas a similar syntax. Called without arguments, the accessor returns the current value of the\nattribute. Called with an argument, the accessor changes the attribute and returns its new\nvalue.\n"
                },
                {
                    "name": "name",
                    "content": "Get or set the cookie's name. Example:\n\n$name = $c->name;\n$newname = $c->name('fred');\n"
                },
                {
                    "name": "value",
                    "content": "Get or set the cookie's value. Example:\n\n$value = $c->value;\n@newvalue = $c->value(['a','b','c','d']);\n\nvalue() is context sensitive. In a list context it will return the current value of the\ncookie as an array. In a scalar context it will return the first value of a multivalued\ncookie.\n"
                },
                {
                    "name": "domain",
                    "content": "Get or set the cookie's domain.\n"
                },
                {
                    "name": "path",
                    "content": "Get or set the cookie's path.\n"
                },
                {
                    "name": "expires",
                    "content": "Get or set the cookie's expiration time.\n"
                },
                {
                    "name": "max_age",
                    "content": "Get or set the cookie's maxage value.\n"
                }
            ]
        },
        "AUTHOR INFORMATION": {
            "content": "The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is distributed under the\nArtistic License 2.0. It is currently maintained by Lee Johnson with help from many\ncontributors.\n\nAddress bug reports and comments to: https://github.com/leejo/CGI.pm/issues\n\nThe original bug tracker can be found at:\nhttps://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm\n\nWhen sending bug reports, please provide the version of CGI.pm, the version of Perl, the name\nand version of your Web server, and the name and version of the operating system you are using.\nIf the problem is even remotely browser dependent, please provide information about the affected\nbrowsers as well.\n",
            "subsections": []
        },
        "BUGS": {
            "content": "This section intentionally left blank.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "CGI::Carp, CGI\n\nRFC 2109 <http://www.ietf.org/rfc/rfc2109.txt>, RFC 2695 <http://www.ietf.org/rfc/rfc2965.txt>\n",
            "subsections": []
        }
    },
    "summary": "CGI::Cookie - Interface to HTTP Cookies",
    "flags": [],
    "examples": [],
    "see_also": []
}