1CGI::Cookie(3) User Contributed Perl Documentation CGI::Cookie(3)
2
3
4
6 CGI::Cookie - Interface to HTTP Cookies
7
9 use CGI qw/:standard/;
10 use CGI::Cookie;
11
12 # Create new cookies and send them
13 $cookie1 = CGI::Cookie->new(-name=>'ID',-value=>123456);
14 $cookie2 = CGI::Cookie->new(-name=>'preferences',
15 -value=>{ font => Helvetica,
16 size => 12 }
17 );
18 print header(-cookie=>[$cookie1,$cookie2]);
19
20 # fetch existing cookies
21 %cookies = CGI::Cookie->fetch;
22 $id = $cookies{'ID'}->value;
23
24 # create cookies returned from an external source
25 %cookies = CGI::Cookie->parse($ENV{COOKIE});
26
28 CGI::Cookie is an interface to HTTP/1.1 cookies, a mechanism that
29 allows Web servers to store persistent information on the browser's
30 side of the connection. Although CGI::Cookie is intended to be used in
31 conjunction with CGI.pm (and is in fact used by it internally), you can
32 use this module independently.
33
34 For full information on cookies see
35
36 https://tools.ietf.org/html/rfc6265
37
39 CGI::Cookie is object oriented. Each cookie object has a name and a
40 value. The name is any scalar value. The value is any scalar or array
41 value (associative arrays are also allowed). Cookies also have several
42 optional attributes, including:
43
44 1. expiration date
45 The expiration date tells the browser how long to hang on to the
46 cookie. If the cookie specifies an expiration date in the future,
47 the browser will store the cookie information in a disk file and
48 return it to the server every time the user reconnects (until the
49 expiration date is reached). If the cookie species an expiration
50 date in the past, the browser will remove the cookie from the disk
51 file. If the expiration date is not specified, the cookie will
52 persist only until the user quits the browser.
53
54 2. domain
55 This is a partial or complete domain name for which the cookie is
56 valid. The browser will return the cookie to any host that matches
57 the partial domain name. For example, if you specify a domain name
58 of ".capricorn.com", then the browser will return the cookie to Web
59 servers running on any of the machines "www.capricorn.com",
60 "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names
61 must contain at least two periods to prevent attempts to match on
62 top level domains like ".edu". If no domain is specified, then the
63 browser will only return the cookie to servers on the host the
64 cookie originated from.
65
66 3. path
67 If you provide a cookie path attribute, the browser will check it
68 against your script's URL before returning the cookie. For
69 example, if you specify the path "/cgi-bin", then the cookie will
70 be returned to each of the scripts "/cgi-bin/tally.pl",
71 "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
72 but not to the script "/cgi-private/site_admin.pl". By default,
73 the path is set to "/", so that all scripts at your site will
74 receive the cookie.
75
76 4. secure flag
77 If the "secure" attribute is set, the cookie will only be sent to
78 your script if the CGI request is occurring on a secure channel,
79 such as SSL.
80
81 5. httponly flag
82 If the "httponly" attribute is set, the cookie will only be
83 accessible through HTTP Requests. This cookie will be inaccessible
84 via JavaScript (to prevent XSS attacks).
85
86 This feature is supported by nearly all modern browsers.
87
88 See these URLs for more information:
89
90 http://msdn.microsoft.com/en-us/library/ms533046.aspx
91 http://www.browserscope.org/?category=security&v=top
92
93 6. samesite flag
94 Allowed settings are "Strict", "Lax" and "None".
95
96 As of June 2016, support is limited to recent releases of Chrome
97 and Opera.
98
99 <https://tools.ietf.org/html/draft-west-first-party-cookies-07>
100
101 7. priority flag
102 Allowed settings are "Low", "Medium" and "High".
103
104 Support is limited to recent releases of Chrome.
105
106 Creating New Cookies
107 my $c = CGI::Cookie->new(-name => 'foo',
108 -value => 'bar',
109 -expires => '+3M',
110 '-max-age' => '+3M',
111 -domain => '.capricorn.com',
112 -path => '/cgi-bin/database',
113 -secure => 1,
114 -samesite=> "Lax",
115 -priority=> "High",
116 );
117
118 Create cookies from scratch with the new method. The -name and -value
119 parameters are required. The name must be a scalar value. The value
120 can be a scalar, an array reference, or a hash reference. (At some
121 point in the future cookies will support one of the Perl object
122 serialization protocols for full generality).
123
124 -expires accepts any of the relative or absolute date formats
125 recognized by CGI.pm, for example "+3M" for three months in the future.
126 See CGI.pm's documentation for details.
127
128 -max-age accepts the same data formats as -expires, but sets a relative
129 value instead of an absolute like -expires. This is intended to be more
130 secure since a clock could be changed to fake an absolute time. In
131 practice, as of 2011, "-max-age" still does not enjoy the widespread
132 support that "-expires" has. You can set both, and browsers that
133 support "-max-age" should ignore the "Expires" header. The drawback to
134 this approach is the bit of bandwidth for sending an extra header on
135 each cookie.
136
137 -domain points to a domain name or to a fully qualified host name. If
138 not specified, the cookie will be returned only to the Web server that
139 created it.
140
141 -path points to a partial URL on the current server. The cookie will
142 be returned to all URLs beginning with the specified path. If not
143 specified, it defaults to '/', which returns the cookie to all pages at
144 your site.
145
146 -secure if set to a true value instructs the browser to return the
147 cookie only when a cryptographic protocol is in use.
148
149 -httponly if set to a true value, the cookie will not be accessible via
150 JavaScript.
151
152 -samesite may be "Lax", "Strict", or "None" and is an evolving part of
153 the standards for cookies. Please refer to current documentation
154 regarding it.
155
156 For compatibility with Apache::Cookie, you may optionally pass in a
157 mod_perl request object as the first argument to new(). It will simply
158 be ignored:
159
160 my $c = CGI::Cookie->new($r,
161 -name => 'foo',
162 -value => ['bar','baz']);
163
164 Sending the Cookie to the Browser
165 The simplest way to send a cookie to the browser is by calling the
166 bake() method:
167
168 $c->bake;
169
170 This will print the Set-Cookie HTTP header to STDOUT using CGI.pm.
171 CGI.pm will be loaded for this purpose if it is not already. Otherwise
172 CGI.pm is not required or used by this module.
173
174 Under mod_perl, pass in an Apache request object:
175
176 $c->bake($r);
177
178 If you want to set the cookie yourself, Within a CGI script you can
179 send a cookie to the browser by creating one or more Set-Cookie: fields
180 in the HTTP header. Here is a typical sequence:
181
182 my $c = CGI::Cookie->new(-name => 'foo',
183 -value => ['bar','baz'],
184 -expires => '+3M');
185
186 print "Set-Cookie: $c\n";
187 print "Content-Type: text/html\n\n";
188
189 To send more than one cookie, create several Set-Cookie: fields.
190
191 If you are using CGI.pm, you send cookies by providing a -cookie
192 argument to the header() method:
193
194 print header(-cookie=>$c);
195
196 Mod_perl users can set cookies using the request object's header_out()
197 method:
198
199 $r->err_headers_out->add('Set-Cookie' => $c);
200
201 Internally, Cookie overloads the "" operator to call its as_string()
202 method when incorporated into the HTTP header. as_string() turns the
203 Cookie's internal representation into an RFC-compliant text
204 representation. You may call as_string() yourself if you prefer:
205
206 print "Set-Cookie: ",$c->as_string,"\n";
207
208 Recovering Previous Cookies
209 %cookies = CGI::Cookie->fetch;
210
211 fetch returns an associative array consisting of all cookies returned
212 by the browser. The keys of the array are the cookie names. You can
213 iterate through the cookies this way:
214
215 %cookies = CGI::Cookie->fetch;
216 for (keys %cookies) {
217 do_something($cookies{$_});
218 }
219
220 In a scalar context, fetch() returns a hash reference, which may be
221 more efficient if you are manipulating multiple cookies.
222
223 CGI.pm uses the URL escaping methods to save and restore reserved
224 characters in its cookies. If you are trying to retrieve a cookie set
225 by a foreign server, this escaping method may trip you up. Use
226 raw_fetch() instead, which has the same semantics as fetch(), but
227 performs no unescaping.
228
229 You may also retrieve cookies that were stored in some external form
230 using the parse() class method:
231
232 $COOKIES = `cat /usr/tmp/Cookie_stash`;
233 %cookies = CGI::Cookie->parse($COOKIES);
234
235 If you are in a mod_perl environment, you can save some overhead by
236 passing the request object to fetch() like this:
237
238 CGI::Cookie->fetch($r);
239
240 If the value passed to parse() is undefined, an empty array will
241 returned in list context, and an empty hashref will be returned in
242 scalar context.
243
244 Manipulating Cookies
245 Cookie objects have a series of accessor methods to get and set cookie
246 attributes. Each accessor has a similar syntax. Called without
247 arguments, the accessor returns the current value of the attribute.
248 Called with an argument, the accessor changes the attribute and returns
249 its new value.
250
251 name()
252 Get or set the cookie's name. Example:
253
254 $name = $c->name;
255 $new_name = $c->name('fred');
256
257 value()
258 Get or set the cookie's value. Example:
259
260 $value = $c->value;
261 @new_value = $c->value(['a','b','c','d']);
262
263 value() is context sensitive. In a list context it will return the
264 current value of the cookie as an array. In a scalar context it
265 will return the first value of a multivalued cookie.
266
267 domain()
268 Get or set the cookie's domain.
269
270 path()
271 Get or set the cookie's path.
272
273 expires()
274 Get or set the cookie's expiration time.
275
276 max_age()
277 Get or set the cookie's max_age value.
278
280 The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is
281 distributed under the Artistic License 2.0. It is currently maintained
282 by Lee Johnson with help from many contributors.
283
284 Address bug reports and comments to:
285 https://github.com/leejo/CGI.pm/issues
286
287 The original bug tracker can be found at:
288 https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm
289
290 When sending bug reports, please provide the version of CGI.pm, the
291 version of Perl, the name and version of your Web server, and the name
292 and version of the operating system you are using. If the problem is
293 even remotely browser dependent, please provide information about the
294 affected browsers as well.
295
297 This section intentionally left blank.
298
300 CGI::Carp, CGI
301
302 RFC 2109 <http://www.ietf.org/rfc/rfc2109.txt>, RFC 2695
303 <http://www.ietf.org/rfc/rfc2965.txt>
304
305
306
307perl v5.36.1 2023-05-04 CGI::Cookie(3)