Commit | Line | Data |
424ec8fa |
1 | package CGI::Cookie; |
2 | |
3 | # See the bottom of this file for the POD documentation. Search for the |
4 | # string '=head'. |
5 | |
6 | # You can run this file through either pod2man or pod2html to produce pretty |
7 | # documentation in manual or html file format (these utilities are part of the |
8 | # Perl 5 distribution). |
9 | |
3538e1d5 |
10 | # Copyright 1995-1999, Lincoln D. Stein. All rights reserved. |
424ec8fa |
11 | # It may be used and modified freely, but I do request that this copyright |
12 | # notice remain attached to the file. You may modify this module as you |
13 | # wish, but if you redistribute a modified version, please attach a note |
14 | # listing the modifications you have made. |
15 | |
3538e1d5 |
16 | $CGI::Cookie::VERSION='1.10'; |
424ec8fa |
17 | |
18 | use CGI; |
19 | use overload '""' => \&as_string, |
20 | 'cmp' => \&compare, |
21 | 'fallback'=>1; |
22 | |
23 | # fetch a list of cookies from the environment and |
24 | # return as a hash. the cookies are parsed as normal |
25 | # escaped URL data. |
26 | sub fetch { |
27 | my $class = shift; |
28 | my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE}; |
29 | return () unless $raw_cookie; |
30 | return $class->parse($raw_cookie); |
31 | } |
32 | |
33 | # fetch a list of cookies from the environment and |
34 | # return as a hash. the cookie values are not unescaped |
35 | # or altered in any way. |
36 | sub raw_fetch { |
37 | my $class = shift; |
38 | my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE}; |
39 | return () unless $raw_cookie; |
40 | my %results; |
41 | my($key,$value); |
42 | |
43 | my(@pairs) = split("; ",$raw_cookie); |
44 | foreach (@pairs) { |
45 | if (/^([^=]+)=(.*)/) { |
46 | $key = $1; |
47 | $value = $2; |
48 | } |
49 | else { |
50 | $key = $_; |
51 | $value = ''; |
52 | } |
53 | $results{$key} = $value; |
54 | } |
55 | return \%results unless wantarray; |
56 | return %results; |
57 | } |
58 | |
59 | sub parse { |
60 | my ($self,$raw_cookie) = @_; |
61 | my %results; |
62 | |
63 | my(@pairs) = split("; ",$raw_cookie); |
64 | foreach (@pairs) { |
65 | my($key,$value) = split("="); |
66 | my(@values) = map CGI::unescape($_),split('&',$value); |
67 | $key = CGI::unescape($key); |
71f3e297 |
68 | # A bug in Netscape can cause several cookies with same name to |
69 | # appear. The FIRST one in HTTP_COOKIE is the most recent version. |
70 | $results{$key} ||= $self->new(-name=>$key,-value=>\@values); |
424ec8fa |
71 | } |
72 | return \%results unless wantarray; |
73 | return %results; |
74 | } |
75 | |
76 | sub new { |
77 | my $class = shift; |
78 | $class = ref($class) if ref($class); |
79 | my($name,$value,$path,$domain,$secure,$expires) = |
80 | CGI->rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@_); |
81 | |
82 | # Pull out our parameters. |
83 | my @values; |
84 | if (ref($value)) { |
85 | if (ref($value) eq 'ARRAY') { |
86 | @values = @$value; |
87 | } elsif (ref($value) eq 'HASH') { |
88 | @values = %$value; |
89 | } |
90 | } else { |
91 | @values = ($value); |
92 | } |
93 | |
94 | bless my $self = { |
95 | 'name'=>$name, |
96 | 'value'=>[@values], |
97 | },$class; |
98 | |
3538e1d5 |
99 | # IE requires the path and domain to be present for some reason. |
100 | $path ||= CGI::url(-absolute=>1); |
101 | $domain ||= CGI::virtual_host(); |
424ec8fa |
102 | |
103 | $self->path($path) if defined $path; |
104 | $self->domain($domain) if defined $domain; |
105 | $self->secure($secure) if defined $secure; |
106 | $self->expires($expires) if defined $expires; |
107 | return $self; |
108 | } |
109 | |
110 | sub as_string { |
111 | my $self = shift; |
112 | return "" unless $self->name; |
113 | |
114 | my(@constant_values,$domain,$path,$expires,$secure); |
115 | |
116 | push(@constant_values,"domain=$domain") if $domain = $self->domain; |
117 | push(@constant_values,"path=$path") if $path = $self->path; |
118 | push(@constant_values,"expires=$expires") if $expires = $self->expires; |
119 | push(@constant_values,'secure') if $secure = $self->secure; |
120 | |
121 | my($key) = CGI::escape($self->name); |
122 | my($cookie) = join("=",$key,join("&",map CGI::escape($_),$self->value)); |
123 | return join("; ",$cookie,@constant_values); |
124 | } |
125 | |
126 | sub compare { |
127 | my $self = shift; |
128 | my $value = shift; |
129 | return "$self" cmp $value; |
130 | } |
131 | |
132 | # accessors |
133 | sub name { |
134 | my $self = shift; |
135 | my $name = shift; |
136 | $self->{'name'} = $name if defined $name; |
137 | return $self->{'name'}; |
138 | } |
139 | |
140 | sub value { |
141 | my $self = shift; |
142 | my $value = shift; |
143 | $self->{'value'} = $value if defined $value; |
144 | return wantarray ? @{$self->{'value'}} : $self->{'value'}->[0] |
145 | } |
146 | |
147 | sub domain { |
148 | my $self = shift; |
149 | my $domain = shift; |
150 | $self->{'domain'} = $domain if defined $domain; |
151 | return $self->{'domain'}; |
152 | } |
153 | |
154 | sub secure { |
155 | my $self = shift; |
156 | my $secure = shift; |
157 | $self->{'secure'} = $secure if defined $secure; |
158 | return $self->{'secure'}; |
159 | } |
160 | |
161 | sub expires { |
162 | my $self = shift; |
163 | my $expires = shift; |
164 | $self->{'expires'} = CGI::expires($expires,'cookie') if defined $expires; |
165 | return $self->{'expires'}; |
166 | } |
167 | |
168 | sub path { |
169 | my $self = shift; |
170 | my $path = shift; |
171 | $self->{'path'} = $path if defined $path; |
172 | return $self->{'path'}; |
173 | } |
174 | |
175 | 1; |
176 | |
177 | =head1 NAME |
178 | |
179 | CGI::Cookie - Interface to Netscape Cookies |
180 | |
181 | =head1 SYNOPSIS |
182 | |
183 | use CGI qw/:standard/; |
184 | use CGI::Cookie; |
185 | |
186 | # Create new cookies and send them |
187 | $cookie1 = new CGI::Cookie(-name=>'ID',-value=>123456); |
188 | $cookie2 = new CGI::Cookie(-name=>'preferences', |
189 | -value=>{ font => Helvetica, |
190 | size => 12 } |
191 | ); |
192 | print header(-cookie=>[$cookie1,$cookie2]); |
193 | |
194 | # fetch existing cookies |
195 | %cookies = fetch CGI::Cookie; |
196 | $id = $cookies{'ID'}->value; |
197 | |
198 | # create cookies returned from an external source |
199 | %cookies = parse CGI::Cookie($ENV{COOKIE}); |
200 | |
201 | =head1 DESCRIPTION |
202 | |
203 | CGI::Cookie is an interface to Netscape (HTTP/1.1) cookies, an |
204 | innovation that allows Web servers to store persistent information on |
205 | the browser's side of the connection. Although CGI::Cookie is |
206 | intended to be used in conjunction with CGI.pm (and is in fact used by |
207 | it internally), you can use this module independently. |
208 | |
209 | For full information on cookies see |
210 | |
211 | http://www.ics.uci.edu/pub/ietf/http/rfc2109.txt |
212 | |
213 | =head1 USING CGI::Cookie |
214 | |
215 | CGI::Cookie is object oriented. Each cookie object has a name and a |
216 | value. The name is any scalar value. The value is any scalar or |
217 | array value (associative arrays are also allowed). Cookies also have |
218 | several optional attributes, including: |
219 | |
220 | =over 4 |
221 | |
222 | =item B<1. expiration date> |
223 | |
224 | The expiration date tells the browser how long to hang on to the |
225 | cookie. If the cookie specifies an expiration date in the future, the |
226 | browser will store the cookie information in a disk file and return it |
227 | to the server every time the user reconnects (until the expiration |
228 | date is reached). If the cookie species an expiration date in the |
229 | past, the browser will remove the cookie from the disk file. If the |
230 | expiration date is not specified, the cookie will persist only until |
231 | the user quits the browser. |
232 | |
233 | =item B<2. domain> |
234 | |
235 | This is a partial or complete domain name for which the cookie is |
236 | valid. The browser will return the cookie to any host that matches |
237 | the partial domain name. For example, if you specify a domain name |
238 | of ".capricorn.com", then Netscape will return the cookie to |
239 | Web servers running on any of the machines "www.capricorn.com", |
240 | "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names |
241 | must contain at least two periods to prevent attempts to match |
242 | on top level domains like ".edu". If no domain is specified, then |
243 | the browser will only return the cookie to servers on the host the |
244 | cookie originated from. |
245 | |
246 | =item B<3. path> |
247 | |
248 | If you provide a cookie path attribute, the browser will check it |
249 | against your script's URL before returning the cookie. For example, |
250 | if you specify the path "/cgi-bin", then the cookie will be returned |
3538e1d5 |
251 | to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and |
252 | "/cgi-bin/customer_service/complain.pl", but not to the script |
253 | "/cgi-private/site_admin.pl". By default, the path is set to the |
254 | directory that contains your script. |
424ec8fa |
255 | |
256 | =item B<4. secure flag> |
257 | |
258 | If the "secure" attribute is set, the cookie will only be sent to your |
259 | script if the CGI request is occurring on a secure channel, such as SSL. |
260 | |
261 | =back |
262 | |
263 | =head2 Creating New Cookies |
264 | |
265 | $c = new CGI::Cookie(-name => 'foo', |
266 | -value => 'bar', |
267 | -expires => '+3M', |
268 | -domain => '.capricorn.com', |
269 | -path => '/cgi-bin/database' |
270 | -secure => 1 |
271 | ); |
272 | |
273 | Create cookies from scratch with the B<new> method. The B<-name> and |
274 | B<-value> parameters are required. The name must be a scalar value. |
275 | The value can be a scalar, an array reference, or a hash reference. |
276 | (At some point in the future cookies will support one of the Perl |
277 | object serialization protocols for full generality). |
278 | |
279 | B<-expires> accepts any of the relative or absolute date formats |
280 | recognized by CGI.pm, for example "+3M" for three months in the |
281 | future. See CGI.pm's documentation for details. |
282 | |
283 | B<-domain> points to a domain name or to a fully qualified host name. |
284 | If not specified, the cookie will be returned only to the Web server |
285 | that created it. |
286 | |
287 | B<-path> points to a partial URL on the current server. The cookie |
288 | will be returned to all URLs beginning with the specified path. If |
289 | not specified, it defaults to '/', which returns the cookie to all |
290 | pages at your site. |
291 | |
292 | B<-secure> if set to a true value instructs the browser to return the |
293 | cookie only when a cryptographic protocol is in use. |
294 | |
295 | =head2 Sending the Cookie to the Browser |
296 | |
297 | Within a CGI script you can send a cookie to the browser by creating |
298 | one or more Set-Cookie: fields in the HTTP header. Here is a typical |
299 | sequence: |
300 | |
301 | my $c = new CGI::Cookie(-name => 'foo', |
302 | -value => ['bar','baz'], |
303 | -expires => '+3M'); |
304 | |
305 | print "Set-Cookie: $c\n"; |
306 | print "Content-Type: text/html\n\n"; |
307 | |
308 | To send more than one cookie, create several Set-Cookie: fields. |
309 | Alternatively, you may concatenate the cookies together with "; " and |
310 | send them in one field. |
311 | |
312 | If you are using CGI.pm, you send cookies by providing a -cookie |
313 | argument to the header() method: |
314 | |
315 | print header(-cookie=>$c); |
316 | |
317 | Mod_perl users can set cookies using the request object's header_out() |
318 | method: |
319 | |
320 | $r->header_out('Set-Cookie',$c); |
321 | |
322 | Internally, Cookie overloads the "" operator to call its as_string() |
323 | method when incorporated into the HTTP header. as_string() turns the |
324 | Cookie's internal representation into an RFC-compliant text |
325 | representation. You may call as_string() yourself if you prefer: |
326 | |
327 | print "Set-Cookie: ",$c->as_string,"\n"; |
328 | |
329 | =head2 Recovering Previous Cookies |
330 | |
331 | %cookies = fetch CGI::Cookie; |
332 | |
333 | B<fetch> returns an associative array consisting of all cookies |
334 | returned by the browser. The keys of the array are the cookie names. You |
335 | can iterate through the cookies this way: |
336 | |
337 | %cookies = fetch CGI::Cookie; |
338 | foreach (keys %cookies) { |
339 | do_something($cookies{$_}); |
340 | } |
341 | |
342 | In a scalar context, fetch() returns a hash reference, which may be more |
343 | efficient if you are manipulating multiple cookies. |
344 | |
345 | CGI.pm uses the URL escaping methods to save and restore reserved characters |
346 | in its cookies. If you are trying to retrieve a cookie set by a foreign server, |
347 | this escaping method may trip you up. Use raw_fetch() instead, which has the |
348 | same semantics as fetch(), but performs no unescaping. |
349 | |
350 | You may also retrieve cookies that were stored in some external |
351 | form using the parse() class method: |
352 | |
353 | $COOKIES = `cat /usr/tmp/Cookie_stash`; |
354 | %cookies = parse CGI::Cookie($COOKIES); |
355 | |
356 | =head2 Manipulating Cookies |
357 | |
358 | Cookie objects have a series of accessor methods to get and set cookie |
359 | attributes. Each accessor has a similar syntax. Called without |
360 | arguments, the accessor returns the current value of the attribute. |
361 | Called with an argument, the accessor changes the attribute and |
362 | returns its new value. |
363 | |
364 | =over 4 |
365 | |
366 | =item B<name()> |
367 | |
368 | Get or set the cookie's name. Example: |
369 | |
370 | $name = $c->name; |
371 | $new_name = $c->name('fred'); |
372 | |
373 | =item B<value()> |
374 | |
375 | Get or set the cookie's value. Example: |
376 | |
377 | $value = $c->value; |
378 | @new_value = $c->value(['a','b','c','d']); |
379 | |
380 | B<value()> is context sensitive. In an array context it will return |
381 | the current value of the cookie as an array. In a scalar context it |
382 | will return the B<first> value of a multivalued cookie. |
383 | |
384 | =item B<domain()> |
385 | |
386 | Get or set the cookie's domain. |
387 | |
388 | =item B<path()> |
389 | |
390 | Get or set the cookie's path. |
391 | |
392 | =item B<expires()> |
393 | |
394 | Get or set the cookie's expiration time. |
395 | |
396 | =back |
397 | |
398 | |
399 | =head1 AUTHOR INFORMATION |
400 | |
71f3e297 |
401 | Copyright 1997-1998, Lincoln D. Stein. All rights reserved. |
424ec8fa |
402 | |
71f3e297 |
403 | This library is free software; you can redistribute it and/or modify |
404 | it under the same terms as Perl itself. |
405 | |
406 | Address bug reports and comments to: lstein@cshl.org |
424ec8fa |
407 | |
408 | =head1 BUGS |
409 | |
410 | This section intentionally left blank. |
411 | |
412 | =head1 SEE ALSO |
413 | |
414 | L<CGI::Carp>, L<CGI> |
415 | |
416 | =cut |