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" and "Lax".
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 Creating New Cookies
102 my $c = CGI::Cookie->new(-name => 'foo',
103 -value => 'bar',
104 -expires => '+3M',
105 '-max-age' => '+3M',
106 -domain => '.capricorn.com',
107 -path => '/cgi-bin/database',
108 -secure => 1,
109 -samesite=> "Lax"
110 );
111
112 Create cookies from scratch with the new method. The -name and -value
113 parameters are required. The name must be a scalar value. The value
114 can be a scalar, an array reference, or a hash reference. (At some
115 point in the future cookies will support one of the Perl object
116 serialization protocols for full generality).
117
118 -expires accepts any of the relative or absolute date formats
119 recognized by CGI.pm, for example "+3M" for three months in the future.
120 See CGI.pm's documentation for details.
121
122 -max-age accepts the same data formats as -expires, but sets a relative
123 value instead of an absolute like -expires. This is intended to be more
124 secure since a clock could be changed to fake an absolute time. In
125 practice, as of 2011, "-max-age" still does not enjoy the widespread
126 support that "-expires" has. You can set both, and browsers that
127 support "-max-age" should ignore the "Expires" header. The drawback to
128 this approach is the bit of bandwidth for sending an extra header on
129 each cookie.
130
131 -domain points to a domain name or to a fully qualified host name. If
132 not specified, the cookie will be returned only to the Web server that
133 created it.
134
135 -path points to a partial URL on the current server. The cookie will
136 be returned to all URLs beginning with the specified path. If not
137 specified, it defaults to '/', which returns the cookie to all pages at
138 your site.
139
140 -secure if set to a true value instructs the browser to return the
141 cookie only when a cryptographic protocol is in use.
142
143 -httponly if set to a true value, the cookie will not be accessible via
144 JavaScript.
145
146 -samesite may be "Lax" or "Strict" and is an evolving part of the
147 standards for cookies. Please refer to current documentation regarding
148 it.
149
150 For compatibility with Apache::Cookie, you may optionally pass in a
151 mod_perl request object as the first argument to "new()". It will
152 simply be ignored:
153
154 my $c = CGI::Cookie->new($r,
155 -name => 'foo',
156 -value => ['bar','baz']);
157
158 Sending the Cookie to the Browser
159 The simplest way to send a cookie to the browser is by calling the
160 bake() method:
161
162 $c->bake;
163
164 This will print the Set-Cookie HTTP header to STDOUT using CGI.pm.
165 CGI.pm will be loaded for this purpose if it is not already. Otherwise
166 CGI.pm is not required or used by this module.
167
168 Under mod_perl, pass in an Apache request object:
169
170 $c->bake($r);
171
172 If you want to set the cookie yourself, Within a CGI script you can
173 send a cookie to the browser by creating one or more Set-Cookie: fields
174 in the HTTP header. Here is a typical sequence:
175
176 my $c = CGI::Cookie->new(-name => 'foo',
177 -value => ['bar','baz'],
178 -expires => '+3M');
179
180 print "Set-Cookie: $c\n";
181 print "Content-Type: text/html\n\n";
182
183 To send more than one cookie, create several Set-Cookie: fields.
184
185 If you are using CGI.pm, you send cookies by providing a -cookie
186 argument to the header() method:
187
188 print header(-cookie=>$c);
189
190 Mod_perl users can set cookies using the request object's header_out()
191 method:
192
193 $r->headers_out->set('Set-Cookie' => $c);
194
195 Internally, Cookie overloads the "" operator to call its as_string()
196 method when incorporated into the HTTP header. as_string() turns the
197 Cookie's internal representation into an RFC-compliant text
198 representation. You may call as_string() yourself if you prefer:
199
200 print "Set-Cookie: ",$c->as_string,"\n";
201
202 Recovering Previous Cookies
203 %cookies = CGI::Cookie->fetch;
204
205 fetch returns an associative array consisting of all cookies returned
206 by the browser. The keys of the array are the cookie names. You can
207 iterate through the cookies this way:
208
209 %cookies = CGI::Cookie->fetch;
210 for (keys %cookies) {
211 do_something($cookies{$_});
212 }
213
214 In a scalar context, fetch() returns a hash reference, which may be
215 more efficient if you are manipulating multiple cookies.
216
217 CGI.pm uses the URL escaping methods to save and restore reserved
218 characters in its cookies. If you are trying to retrieve a cookie set
219 by a foreign server, this escaping method may trip you up. Use
220 raw_fetch() instead, which has the same semantics as fetch(), but
221 performs no unescaping.
222
223 You may also retrieve cookies that were stored in some external form
224 using the parse() class method:
225
226 $COOKIES = `cat /usr/tmp/Cookie_stash`;
227 %cookies = CGI::Cookie->parse($COOKIES);
228
229 If you are in a mod_perl environment, you can save some overhead by
230 passing the request object to fetch() like this:
231
232 CGI::Cookie->fetch($r);
233
234 If the value passed to parse() is undefined, an empty array will
235 returned in list context, and an empty hashref will be returned in
236 scalar context.
237
238 Manipulating Cookies
239 Cookie objects have a series of accessor methods to get and set cookie
240 attributes. Each accessor has a similar syntax. Called without
241 arguments, the accessor returns the current value of the attribute.
242 Called with an argument, the accessor changes the attribute and returns
243 its new value.
244
245 name()
246 Get or set the cookie's name. Example:
247
248 $name = $c->name;
249 $new_name = $c->name('fred');
250
251 value()
252 Get or set the cookie's value. Example:
253
254 $value = $c->value;
255 @new_value = $c->value(['a','b','c','d']);
256
257 value() is context sensitive. In a list context it will return the
258 current value of the cookie as an array. In a scalar context it
259 will return the first value of a multivalued cookie.
260
261 domain()
262 Get or set the cookie's domain.
263
264 path()
265 Get or set the cookie's path.
266
267 expires()
268 Get or set the cookie's expiration time.
269
270 max_age()
271 Get or set the cookie's max_age value.
272
274 The CGI.pm distribution is copyright 1995-2007, Lincoln D. Stein. It is
275 distributed under GPL and the Artistic License 2.0. It is currently
276 maintained by Lee Johnson with help from many contributors.
277
278 Address bug reports and comments to:
279 https://github.com/leejo/CGI.pm/issues
280
281 The original bug tracker can be found at:
282 https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm
283
284 When sending bug reports, please provide the version of CGI.pm, the
285 version of Perl, the name and version of your Web server, and the name
286 and version of the operating system you are using. If the problem is
287 even remotely browser dependent, please provide information about the
288 affected browsers as well.
289
291 This section intentionally left blank.
292
294 CGI::Carp, CGI
295
296 RFC 2109 <http://www.ietf.org/rfc/rfc2109.txt>, RFC 2695
297 <http://www.ietf.org/rfc/rfc2965.txt>
298
299
300
301perl v5.26.3 2017-12-01 CGI::Cookie(3)