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.27';
18 use CGI::Util qw(rearrange unescape escape);
20 use overload '""' => \&as_string,
24 # Turn on special checking for Doug MacEachern's modperl
26 if (exists $ENV{MOD_PERL}) {
27 if (exists $ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) {
29 require Apache2::RequestUtil;
37 # fetch a list of cookies from the environment and
38 # return as a hash. the cookies are parsed as normal
42 my $raw_cookie = get_raw_cookie(@_) or return;
43 return $class->parse($raw_cookie);
46 # Fetch a list of cookies from the environment or the incoming headers and
47 # return as a hash. The cookie values are not unescaped or altered in any way.
50 my $raw_cookie = get_raw_cookie(@_) or return;
54 my(@pairs) = split("; ?",$raw_cookie);
57 if (/^([^=]+)=(.*)/) {
65 $results{$key} = $value;
67 return \%results unless wantarray;
73 $r ||= eval { $MOD_PERL == 2 ?
74 Apache2::RequestUtil->request() :
75 Apache->request } if $MOD_PERL;
77 $raw_cookie = $r->headers_in->{'Cookie'};
79 if ($MOD_PERL && !exists $ENV{REQUEST_METHOD}) {
80 die "Run $r->subprocess_env; before calling fetch()";
82 $raw_cookie = $ENV{HTTP_COOKIE} || $ENV{COOKIE};
88 my ($self,$raw_cookie) = @_;
91 my(@pairs) = split("; ?",$raw_cookie);
94 my($key,$value) = split("=",$_,2);
96 # Some foreign cookies are not in name=value format, so ignore
98 next if !defined($value);
101 @values = map unescape($_),split(/[&;]/,$value.'&dmy');
104 $key = unescape($key);
105 # A bug in Netscape can cause several cookies with same name to
106 # appear. The FIRST one in HTTP_COOKIE is the most recent version.
107 $results{$key} ||= $self->new(-name=>$key,-value=>\@values);
109 return \%results unless wantarray;
115 $class = ref($class) if ref($class);
116 # Ignore mod_perl request object--compatability with Apache::Cookie.
118 && eval { $_[0]->isa('Apache::Request::Req') || $_[0]->isa('Apache') };
119 my($name,$value,$path,$domain,$secure,$expires) =
120 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@_);
122 # Pull out our parameters.
125 if (ref($value) eq 'ARRAY') {
127 } elsif (ref($value) eq 'HASH') {
139 # IE requires the path and domain to be present for some reason.
141 # however, this breaks networks which use host tables without fully qualified
142 # names, so we comment it out.
143 # $domain = CGI::virtual_host() unless defined $domain;
145 $self->path($path) if defined $path;
146 $self->domain($domain) if defined $domain;
147 $self->secure($secure) if defined $secure;
148 $self->expires($expires) if defined $expires;
149 # $self->max_age($expires) if defined $expires;
155 return "" unless $self->name;
157 my(@constant_values,$domain,$path,$expires,$max_age,$secure);
159 push(@constant_values,"domain=$domain") if $domain = $self->domain;
160 push(@constant_values,"path=$path") if $path = $self->path;
161 push(@constant_values,"expires=$expires") if $expires = $self->expires;
162 push(@constant_values,"max-age=$max_age") if $max_age = $self->max_age;
163 push(@constant_values,"secure") if $secure = $self->secure;
165 my($key) = escape($self->name);
166 my($cookie) = join("=",(defined $key ? $key : ''),join("&",map escape(defined $_ ? $_ : ''),$self->value));
167 return join("; ",$cookie,@constant_values);
173 return "$self" cmp $value;
181 ? Apache2::RequestUtil->request()
185 $r->headers_out->add('Set-Cookie' => $self->as_string);
187 print CGI::header(-cookie => $self);
196 $self->{'name'} = $name if defined $name;
197 return $self->{'name'};
203 if (defined $value) {
206 if (ref($value) eq 'ARRAY') {
208 } elsif (ref($value) eq 'HASH') {
214 $self->{'value'} = [@values];
216 return wantarray ? @{$self->{'value'}} : $self->{'value'}->[0]
222 $self->{'domain'} = lc $domain if defined $domain;
223 return $self->{'domain'};
229 $self->{'secure'} = $secure if defined $secure;
230 return $self->{'secure'};
236 $self->{'expires'} = CGI::Util::expires($expires,'cookie') if defined $expires;
237 return $self->{'expires'};
243 $self->{'max-age'} = CGI::Util::expire_calc($expires)-time() if defined $expires;
244 return $self->{'max-age'};
250 $self->{'path'} = $path if defined $path;
251 return $self->{'path'};
258 CGI::Cookie - Interface to Netscape Cookies
262 use CGI qw/:standard/;
265 # Create new cookies and send them
266 $cookie1 = new CGI::Cookie(-name=>'ID',-value=>123456);
267 $cookie2 = new CGI::Cookie(-name=>'preferences',
268 -value=>{ font => Helvetica,
271 print header(-cookie=>[$cookie1,$cookie2]);
273 # fetch existing cookies
274 %cookies = fetch CGI::Cookie;
275 $id = $cookies{'ID'}->value;
277 # create cookies returned from an external source
278 %cookies = parse CGI::Cookie($ENV{COOKIE});
282 CGI::Cookie is an interface to Netscape (HTTP/1.1) cookies, an
283 innovation that allows Web servers to store persistent information on
284 the browser's side of the connection. Although CGI::Cookie is
285 intended to be used in conjunction with CGI.pm (and is in fact used by
286 it internally), you can use this module independently.
288 For full information on cookies see
290 http://www.ics.uci.edu/pub/ietf/http/rfc2109.txt
292 =head1 USING CGI::Cookie
294 CGI::Cookie is object oriented. Each cookie object has a name and a
295 value. The name is any scalar value. The value is any scalar or
296 array value (associative arrays are also allowed). Cookies also have
297 several optional attributes, including:
301 =item B<1. expiration date>
303 The expiration date tells the browser how long to hang on to the
304 cookie. If the cookie specifies an expiration date in the future, the
305 browser will store the cookie information in a disk file and return it
306 to the server every time the user reconnects (until the expiration
307 date is reached). If the cookie species an expiration date in the
308 past, the browser will remove the cookie from the disk file. If the
309 expiration date is not specified, the cookie will persist only until
310 the user quits the browser.
314 This is a partial or complete domain name for which the cookie is
315 valid. The browser will return the cookie to any host that matches
316 the partial domain name. For example, if you specify a domain name
317 of ".capricorn.com", then Netscape will return the cookie to
318 Web servers running on any of the machines "www.capricorn.com",
319 "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names
320 must contain at least two periods to prevent attempts to match
321 on top level domains like ".edu". If no domain is specified, then
322 the browser will only return the cookie to servers on the host the
323 cookie originated from.
327 If you provide a cookie path attribute, the browser will check it
328 against your script's URL before returning the cookie. For example,
329 if you specify the path "/cgi-bin", then the cookie will be returned
330 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and
331 "/cgi-bin/customer_service/complain.pl", but not to the script
332 "/cgi-private/site_admin.pl". By default, the path is set to "/", so
333 that all scripts at your site will receive the cookie.
335 =item B<4. secure flag>
337 If the "secure" attribute is set, the cookie will only be sent to your
338 script if the CGI request is occurring on a secure channel, such as SSL.
342 =head2 Creating New Cookies
344 my $c = new CGI::Cookie(-name => 'foo',
347 -domain => '.capricorn.com',
348 -path => '/cgi-bin/database',
352 Create cookies from scratch with the B<new> method. The B<-name> and
353 B<-value> parameters are required. The name must be a scalar value.
354 The value can be a scalar, an array reference, or a hash reference.
355 (At some point in the future cookies will support one of the Perl
356 object serialization protocols for full generality).
358 B<-expires> accepts any of the relative or absolute date formats
359 recognized by CGI.pm, for example "+3M" for three months in the
360 future. See CGI.pm's documentation for details.
362 B<-domain> points to a domain name or to a fully qualified host name.
363 If not specified, the cookie will be returned only to the Web server
366 B<-path> points to a partial URL on the current server. The cookie
367 will be returned to all URLs beginning with the specified path. If
368 not specified, it defaults to '/', which returns the cookie to all
371 B<-secure> if set to a true value instructs the browser to return the
372 cookie only when a cryptographic protocol is in use.
374 For compatibility with Apache::Cookie, you may optionally pass in
375 a mod_perl request object as the first argument to C<new()>. It will
378 my $c = new CGI::Cookie($r,
380 -value => ['bar','baz']);
382 =head2 Sending the Cookie to the Browser
384 The simplest way to send a cookie to the browser is by calling the bake()
389 Under mod_perl, pass in an Apache request object:
393 If you want to set the cookie yourself, Within a CGI script you can send
394 a cookie to the browser by creating one or more Set-Cookie: fields in the
395 HTTP header. Here is a typical sequence:
397 my $c = new CGI::Cookie(-name => 'foo',
398 -value => ['bar','baz'],
401 print "Set-Cookie: $c\n";
402 print "Content-Type: text/html\n\n";
404 To send more than one cookie, create several Set-Cookie: fields.
406 If you are using CGI.pm, you send cookies by providing a -cookie
407 argument to the header() method:
409 print header(-cookie=>$c);
411 Mod_perl users can set cookies using the request object's header_out()
414 $r->headers_out->set('Set-Cookie' => $c);
416 Internally, Cookie overloads the "" operator to call its as_string()
417 method when incorporated into the HTTP header. as_string() turns the
418 Cookie's internal representation into an RFC-compliant text
419 representation. You may call as_string() yourself if you prefer:
421 print "Set-Cookie: ",$c->as_string,"\n";
423 =head2 Recovering Previous Cookies
425 %cookies = fetch CGI::Cookie;
427 B<fetch> returns an associative array consisting of all cookies
428 returned by the browser. The keys of the array are the cookie names. You
429 can iterate through the cookies this way:
431 %cookies = fetch CGI::Cookie;
432 foreach (keys %cookies) {
433 do_something($cookies{$_});
436 In a scalar context, fetch() returns a hash reference, which may be more
437 efficient if you are manipulating multiple cookies.
439 CGI.pm uses the URL escaping methods to save and restore reserved characters
440 in its cookies. If you are trying to retrieve a cookie set by a foreign server,
441 this escaping method may trip you up. Use raw_fetch() instead, which has the
442 same semantics as fetch(), but performs no unescaping.
444 You may also retrieve cookies that were stored in some external
445 form using the parse() class method:
447 $COOKIES = `cat /usr/tmp/Cookie_stash`;
448 %cookies = parse CGI::Cookie($COOKIES);
450 If you are in a mod_perl environment, you can save some overhead by
451 passing the request object to fetch() like this:
453 CGI::Cookie->fetch($r);
455 =head2 Manipulating Cookies
457 Cookie objects have a series of accessor methods to get and set cookie
458 attributes. Each accessor has a similar syntax. Called without
459 arguments, the accessor returns the current value of the attribute.
460 Called with an argument, the accessor changes the attribute and
461 returns its new value.
467 Get or set the cookie's name. Example:
470 $new_name = $c->name('fred');
474 Get or set the cookie's value. Example:
477 @new_value = $c->value(['a','b','c','d']);
479 B<value()> is context sensitive. In a list context it will return
480 the current value of the cookie as an array. In a scalar context it
481 will return the B<first> value of a multivalued cookie.
485 Get or set the cookie's domain.
489 Get or set the cookie's path.
493 Get or set the cookie's expiration time.
498 =head1 AUTHOR INFORMATION
500 Copyright 1997-1998, Lincoln D. Stein. All rights reserved.
502 This library is free software; you can redistribute it and/or modify
503 it under the same terms as Perl itself.
505 Address bug reports and comments to: lstein@cshl.org
509 This section intentionally left blank.