3 # See the bottom of this file for the POD documentation. Search for the
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).
10 # Copyright 1995-1999, Lincoln D. Stein. All rights reserved.
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.
16 $CGI::Cookie::VERSION='1.20';
18 use CGI::Util qw(rearrange unescape escape);
19 use overload '""' => \&as_string,
23 # fetch a list of cookies from the environment and
24 # return as a hash. the cookies are parsed as normal
28 my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE};
29 return () unless $raw_cookie;
30 return $class->parse($raw_cookie);
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.
38 my $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE};
39 return () unless $raw_cookie;
43 my(@pairs) = split("; ?",$raw_cookie);
46 if (/^([^=]+)=(.*)/) {
54 $results{$key} = $value;
56 return \%results unless wantarray;
62 my ($self,$raw_cookie) = @_;
65 my(@pairs) = split("; ?",$raw_cookie);
68 my($key,$value) = split("=",$_,2);
70 # Some foreign cookies are not in name=value format, so ignore
72 next if !defined($value);
75 @values = map unescape($_),split(/[&;]/,$value.'&dmy');
78 $key = unescape($key);
79 # A bug in Netscape can cause several cookies with same name to
80 # appear. The FIRST one in HTTP_COOKIE is the most recent version.
81 $results{$key} ||= $self->new(-name=>$key,-value=>\@values);
83 return \%results unless wantarray;
89 $class = ref($class) if ref($class);
90 my($name,$value,$path,$domain,$secure,$expires) =
91 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@_);
93 # Pull out our parameters.
96 if (ref($value) eq 'ARRAY') {
98 } elsif (ref($value) eq 'HASH') {
110 # IE requires the path and domain to be present for some reason.
112 # however, this breaks networks which use host tables without fully qualified
113 # names, so we comment it out.
114 # $domain = CGI::virtual_host() unless defined $domain;
116 $self->path($path) if defined $path;
117 $self->domain($domain) if defined $domain;
118 $self->secure($secure) if defined $secure;
119 $self->expires($expires) if defined $expires;
125 return "" unless $self->name;
127 my(@constant_values,$domain,$path,$expires,$secure);
129 push(@constant_values,"domain=$domain") if $domain = $self->domain;
130 push(@constant_values,"path=$path") if $path = $self->path;
131 push(@constant_values,"expires=$expires") if $expires = $self->expires;
132 push(@constant_values,"secure") if $secure = $self->secure;
134 my($key) = escape($self->name);
135 my($cookie) = join("=",$key,join("&",map escape($_),$self->value));
136 return join("; ",$cookie,@constant_values);
142 return "$self" cmp $value;
149 $self->{'name'} = $name if defined $name;
150 return $self->{'name'};
156 if (defined $value) {
159 if (ref($value) eq 'ARRAY') {
161 } elsif (ref($value) eq 'HASH') {
167 $self->{'value'} = [@values];
169 return wantarray ? @{$self->{'value'}} : $self->{'value'}->[0]
175 $self->{'domain'} = $domain if defined $domain;
176 return $self->{'domain'};
182 $self->{'secure'} = $secure if defined $secure;
183 return $self->{'secure'};
189 $self->{'expires'} = CGI::Util::expires($expires,'cookie') if defined $expires;
190 return $self->{'expires'};
196 $self->{'path'} = $path if defined $path;
197 return $self->{'path'};
204 CGI::Cookie - Interface to Netscape Cookies
208 use CGI qw/:standard/;
211 # Create new cookies and send them
212 $cookie1 = new CGI::Cookie(-name=>'ID',-value=>123456);
213 $cookie2 = new CGI::Cookie(-name=>'preferences',
214 -value=>{ font => Helvetica,
217 print header(-cookie=>[$cookie1,$cookie2]);
219 # fetch existing cookies
220 %cookies = fetch CGI::Cookie;
221 $id = $cookies{'ID'}->value;
223 # create cookies returned from an external source
224 %cookies = parse CGI::Cookie($ENV{COOKIE});
228 CGI::Cookie is an interface to Netscape (HTTP/1.1) cookies, an
229 innovation that allows Web servers to store persistent information on
230 the browser's side of the connection. Although CGI::Cookie is
231 intended to be used in conjunction with CGI.pm (and is in fact used by
232 it internally), you can use this module independently.
234 For full information on cookies see
236 http://www.ics.uci.edu/pub/ietf/http/rfc2109.txt
238 =head1 USING CGI::Cookie
240 CGI::Cookie is object oriented. Each cookie object has a name and a
241 value. The name is any scalar value. The value is any scalar or
242 array value (associative arrays are also allowed). Cookies also have
243 several optional attributes, including:
247 =item B<1. expiration date>
249 The expiration date tells the browser how long to hang on to the
250 cookie. If the cookie specifies an expiration date in the future, the
251 browser will store the cookie information in a disk file and return it
252 to the server every time the user reconnects (until the expiration
253 date is reached). If the cookie species an expiration date in the
254 past, the browser will remove the cookie from the disk file. If the
255 expiration date is not specified, the cookie will persist only until
256 the user quits the browser.
260 This is a partial or complete domain name for which the cookie is
261 valid. The browser will return the cookie to any host that matches
262 the partial domain name. For example, if you specify a domain name
263 of ".capricorn.com", then Netscape will return the cookie to
264 Web servers running on any of the machines "www.capricorn.com",
265 "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names
266 must contain at least two periods to prevent attempts to match
267 on top level domains like ".edu". If no domain is specified, then
268 the browser will only return the cookie to servers on the host the
269 cookie originated from.
273 If you provide a cookie path attribute, the browser will check it
274 against your script's URL before returning the cookie. For example,
275 if you specify the path "/cgi-bin", then the cookie will be returned
276 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and
277 "/cgi-bin/customer_service/complain.pl", but not to the script
278 "/cgi-private/site_admin.pl". By default, the path is set to "/", so
279 that all scripts at your site will receive the cookie.
281 =item B<4. secure flag>
283 If the "secure" attribute is set, the cookie will only be sent to your
284 script if the CGI request is occurring on a secure channel, such as SSL.
288 =head2 Creating New Cookies
290 $c = new CGI::Cookie(-name => 'foo',
293 -domain => '.capricorn.com',
294 -path => '/cgi-bin/database',
298 Create cookies from scratch with the B<new> method. The B<-name> and
299 B<-value> parameters are required. The name must be a scalar value.
300 The value can be a scalar, an array reference, or a hash reference.
301 (At some point in the future cookies will support one of the Perl
302 object serialization protocols for full generality).
304 B<-expires> accepts any of the relative or absolute date formats
305 recognized by CGI.pm, for example "+3M" for three months in the
306 future. See CGI.pm's documentation for details.
308 B<-domain> points to a domain name or to a fully qualified host name.
309 If not specified, the cookie will be returned only to the Web server
312 B<-path> points to a partial URL on the current server. The cookie
313 will be returned to all URLs beginning with the specified path. If
314 not specified, it defaults to '/', which returns the cookie to all
317 B<-secure> if set to a true value instructs the browser to return the
318 cookie only when a cryptographic protocol is in use.
320 =head2 Sending the Cookie to the Browser
322 Within a CGI script you can send a cookie to the browser by creating
323 one or more Set-Cookie: fields in the HTTP header. Here is a typical
326 my $c = new CGI::Cookie(-name => 'foo',
327 -value => ['bar','baz'],
330 print "Set-Cookie: $c\n";
331 print "Content-Type: text/html\n\n";
333 To send more than one cookie, create several Set-Cookie: fields.
334 Alternatively, you may concatenate the cookies together with "; " and
335 send them in one field.
337 If you are using CGI.pm, you send cookies by providing a -cookie
338 argument to the header() method:
340 print header(-cookie=>$c);
342 Mod_perl users can set cookies using the request object's header_out()
345 $r->header_out('Set-Cookie',$c);
347 Internally, Cookie overloads the "" operator to call its as_string()
348 method when incorporated into the HTTP header. as_string() turns the
349 Cookie's internal representation into an RFC-compliant text
350 representation. You may call as_string() yourself if you prefer:
352 print "Set-Cookie: ",$c->as_string,"\n";
354 =head2 Recovering Previous Cookies
356 %cookies = fetch CGI::Cookie;
358 B<fetch> returns an associative array consisting of all cookies
359 returned by the browser. The keys of the array are the cookie names. You
360 can iterate through the cookies this way:
362 %cookies = fetch CGI::Cookie;
363 foreach (keys %cookies) {
364 do_something($cookies{$_});
367 In a scalar context, fetch() returns a hash reference, which may be more
368 efficient if you are manipulating multiple cookies.
370 CGI.pm uses the URL escaping methods to save and restore reserved characters
371 in its cookies. If you are trying to retrieve a cookie set by a foreign server,
372 this escaping method may trip you up. Use raw_fetch() instead, which has the
373 same semantics as fetch(), but performs no unescaping.
375 You may also retrieve cookies that were stored in some external
376 form using the parse() class method:
378 $COOKIES = `cat /usr/tmp/Cookie_stash`;
379 %cookies = parse CGI::Cookie($COOKIES);
381 =head2 Manipulating Cookies
383 Cookie objects have a series of accessor methods to get and set cookie
384 attributes. Each accessor has a similar syntax. Called without
385 arguments, the accessor returns the current value of the attribute.
386 Called with an argument, the accessor changes the attribute and
387 returns its new value.
393 Get or set the cookie's name. Example:
396 $new_name = $c->name('fred');
400 Get or set the cookie's value. Example:
403 @new_value = $c->value(['a','b','c','d']);
405 B<value()> is context sensitive. In a list context it will return
406 the current value of the cookie as an array. In a scalar context it
407 will return the B<first> value of a multivalued cookie.
411 Get or set the cookie's domain.
415 Get or set the cookie's path.
419 Get or set the cookie's expiration time.
424 =head1 AUTHOR INFORMATION
426 Copyright 1997-1998, Lincoln D. Stein. All rights reserved.
428 This library is free software; you can redistribute it and/or modify
429 it under the same terms as Perl itself.
431 Address bug reports and comments to: lstein@cshl.org
435 This section intentionally left blank.