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, an innovation 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 http://tools.ietf.org/html/rfc2109
37 http://tools.ietf.org/html/rfc2965
38 http://tools.ietf.org/html/draft-ietf-httpstate-cookie
39
41 CGI::Cookie is object oriented. Each cookie object has a name and a
42 value. The name is any scalar value. The value is any scalar or array
43 value (associative arrays are also allowed). Cookies also have several
44 optional attributes, including:
45
46 1. expiration date
47 The expiration date tells the browser how long to hang on to the
48 cookie. If the cookie specifies an expiration date in the future,
49 the browser will store the cookie information in a disk file and
50 return it to the server every time the user reconnects (until the
51 expiration date is reached). If the cookie species an expiration
52 date in the past, the browser will remove the cookie from the disk
53 file. If the expiration date is not specified, the cookie will
54 persist only until the user quits the browser.
55
56 2. domain
57 This is a partial or complete domain name for which the cookie is
58 valid. The browser will return the cookie to any host that matches
59 the partial domain name. For example, if you specify a domain name
60 of ".capricorn.com", then the browser will return the cookie to Web
61 servers running on any of the machines "www.capricorn.com",
62 "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names
63 must contain at least two periods to prevent attempts to match on
64 top level domains like ".edu". If no domain is specified, then the
65 browser will only return the cookie to servers on the host the
66 cookie originated from.
67
68 3. path
69 If you provide a cookie path attribute, the browser will check it
70 against your script's URL before returning the cookie. For
71 example, if you specify the path "/cgi-bin", then the cookie will
72 be returned to each of the scripts "/cgi-bin/tally.pl",
73 "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
74 but not to the script "/cgi-private/site_admin.pl". By default,
75 the path is set to "/", so that all scripts at your site will
76 receive the cookie.
77
78 4. secure flag
79 If the "secure" attribute is set, the cookie will only be sent to
80 your script if the CGI request is occurring on a secure channel,
81 such as SSL.
82
83 5. httponly flag
84 If the "httponly" attribute is set, the cookie will only be
85 accessible through HTTP Requests. This cookie will be inaccessible
86 via JavaScript (to prevent XSS attacks).
87
88 This feature is only supported by recent browsers like Internet
89 Explorer 6 Service Pack 1, Firefox 3.0 and Opera 9.5 (and later of
90 course).
91
92 See these URLs for more information:
93
94 http://msdn.microsoft.com/en-us/library/ms533046.aspx
95 http://www.owasp.org/index.php/HTTPOnly#Browsers_Supporting_HTTPOnly
96
97 Creating New Cookies
98 my $c = CGI::Cookie->new(-name => 'foo',
99 -value => 'bar',
100 -expires => '+3M',
101 -domain => '.capricorn.com',
102 -path => '/cgi-bin/database',
103 -secure => 1
104 );
105
106 Create cookies from scratch with the new method. The -name and -value
107 parameters are required. The name must be a scalar value. The value
108 can be a scalar, an array reference, or a hash reference. (At some
109 point in the future cookies will support one of the Perl object
110 serialization protocols for full generality).
111
112 -expires accepts any of the relative or absolute date formats
113 recognized by CGI.pm, for example "+3M" for three months in the future.
114 See CGI.pm's documentation for details.
115
116 -max-age accepts the same data formats as -expires, but sets a relative
117 value instead of an absolute like -expires. This is intended to be more
118 secure since a clock could be changed to fake an absolute time. In
119 practice, as of 2011, "-max-age" still does not enjoy the widespread
120 support that "-expires" has. You can set both, and browsers that
121 support "-max-age" should ignore the "Expires" header. The drawback to
122 this approach is the bit of bandwidth for sending an extra header on
123 each cookie.
124
125 -domain points to a domain name or to a fully qualified host name. If
126 not specified, the cookie will be returned only to the Web server that
127 created it.
128
129 -path points to a partial URL on the current server. The cookie will
130 be returned to all URLs beginning with the specified path. If not
131 specified, it defaults to '/', which returns the cookie to all pages at
132 your site.
133
134 -secure if set to a true value instructs the browser to return the
135 cookie only when a cryptographic protocol is in use.
136
137 -httponly if set to a true value, the cookie will not be accessible via
138 JavaScript.
139
140 For compatibility with Apache::Cookie, you may optionally pass in a
141 mod_perl request object as the first argument to "new()". It will
142 simply be ignored:
143
144 my $c = CGI::Cookie->new($r,
145 -name => 'foo',
146 -value => ['bar','baz']);
147
148 Sending the Cookie to the Browser
149 The simplest way to send a cookie to the browser is by calling the
150 bake() method:
151
152 $c->bake;
153
154 This will print the Set-Cookie HTTP header to STDOUT using CGI.pm.
155 CGI.pm will be loaded for this purpose if it is not already. Otherwise
156 CGI.pm is not required or used by this module.
157
158 Under mod_perl, pass in an Apache request object:
159
160 $c->bake($r);
161
162 If you want to set the cookie yourself, Within a CGI script you can
163 send a cookie to the browser by creating one or more Set-Cookie: fields
164 in the HTTP header. Here is a typical sequence:
165
166 my $c = CGI::Cookie->new(-name => 'foo',
167 -value => ['bar','baz'],
168 -expires => '+3M');
169
170 print "Set-Cookie: $c\n";
171 print "Content-Type: text/html\n\n";
172
173 To send more than one cookie, create several Set-Cookie: fields.
174
175 If you are using CGI.pm, you send cookies by providing a -cookie
176 argument to the header() method:
177
178 print header(-cookie=>$c);
179
180 Mod_perl users can set cookies using the request object's header_out()
181 method:
182
183 $r->headers_out->set('Set-Cookie' => $c);
184
185 Internally, Cookie overloads the "" operator to call its as_string()
186 method when incorporated into the HTTP header. as_string() turns the
187 Cookie's internal representation into an RFC-compliant text
188 representation. You may call as_string() yourself if you prefer:
189
190 print "Set-Cookie: ",$c->as_string,"\n";
191
192 Recovering Previous Cookies
193 %cookies = CGI::Cookie->fetch;
194
195 fetch returns an associative array consisting of all cookies returned
196 by the browser. The keys of the array are the cookie names. You can
197 iterate through the cookies this way:
198
199 %cookies = CGI::Cookie->fetch;
200 for (keys %cookies) {
201 do_something($cookies{$_});
202 }
203
204 In a scalar context, fetch() returns a hash reference, which may be
205 more efficient if you are manipulating multiple cookies.
206
207 CGI.pm uses the URL escaping methods to save and restore reserved
208 characters in its cookies. If you are trying to retrieve a cookie set
209 by a foreign server, this escaping method may trip you up. Use
210 raw_fetch() instead, which has the same semantics as fetch(), but
211 performs no unescaping.
212
213 You may also retrieve cookies that were stored in some external form
214 using the parse() class method:
215
216 $COOKIES = `cat /usr/tmp/Cookie_stash`;
217 %cookies = CGI::Cookie->parse($COOKIES);
218
219 If you are in a mod_perl environment, you can save some overhead by
220 passing the request object to fetch() like this:
221
222 CGI::Cookie->fetch($r);
223
224 If the value passed to parse() is undefined, an empty array will
225 returned in list context, and an empty hashref will be returned in
226 scalar context.
227
228 Manipulating Cookies
229 Cookie objects have a series of accessor methods to get and set cookie
230 attributes. Each accessor has a similar syntax. Called without
231 arguments, the accessor returns the current value of the attribute.
232 Called with an argument, the accessor changes the attribute and returns
233 its new value.
234
235 name()
236 Get or set the cookie's name. Example:
237
238 $name = $c->name;
239 $new_name = $c->name('fred');
240
241 value()
242 Get or set the cookie's value. Example:
243
244 $value = $c->value;
245 @new_value = $c->value(['a','b','c','d']);
246
247 value() is context sensitive. In a list context it will return the
248 current value of the cookie as an array. In a scalar context it
249 will return the first value of a multivalued cookie.
250
251 domain()
252 Get or set the cookie's domain.
253
254 path()
255 Get or set the cookie's path.
256
257 expires()
258 Get or set the cookie's expiration time.
259
261 Copyright 1997-1998, Lincoln D. Stein. All rights reserved.
262
263 This library is free software; you can redistribute it and/or modify it
264 under the same terms as Perl itself.
265
266 Address bug reports and comments to: lstein@cshl.org
267
269 This section intentionally left blank.
270
272 CGI::Carp, CGI
273
274 RFC 2109 <http://www.ietf.org/rfc/rfc2109.txt>, RFC 2695
275 <http://www.ietf.org/rfc/rfc2965.txt>
276
277
278
279perl v5.16.3 2012-08-16 CGI::Cookie(3)