6 # See the bottom of this file for the POD documentation. Search for the
9 # You can run this file through either pod2man or pod2html to produce pretty
10 # documentation in manual or html file format (these utilities are part of the
11 # Perl 5 distribution).
13 # Copyright 1995-1999, Lincoln D. Stein. All rights reserved.
14 # It may be used and modified freely, but I do request that this copyright
15 # notice remain attached to the file. You may modify this module as you
16 # wish, but if you redistribute a modified version, please attach a note
17 # listing the modifications you have made.
19 $CGI::Cookie::VERSION='1.29';
21 use CGI::Util qw(rearrange unescape escape);
23 use overload '""' => \&as_string,
28 # Turn on special checking for ActiveState's PerlEx
29 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
31 # Turn on special checking for Doug MacEachern's modperl
32 # PerlEx::DBI tries to fool DBI by setting MOD_PERL
34 if (exists $ENV{MOD_PERL} && ! $PERLEX) {
35 if (exists $ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) {
37 require Apache2::RequestUtil;
45 # fetch a list of cookies from the environment and
46 # return as a hash. the cookies are parsed as normal
50 my $raw_cookie = get_raw_cookie(@_) or return;
51 return $class->parse($raw_cookie);
54 # Fetch a list of cookies from the environment or the incoming headers and
55 # return as a hash. The cookie values are not unescaped or altered in any way.
58 my $raw_cookie = get_raw_cookie(@_) or return;
62 my @pairs = split("[;,] ?",$raw_cookie);
65 if (/^([^=]+)=(.*)/) {
73 $results{$key} = $value;
75 return \%results unless wantarray;
81 $r ||= eval { $MOD_PERL == 2 ?
82 Apache2::RequestUtil->request() :
83 Apache->request } if $MOD_PERL;
85 return $r->headers_in->{'Cookie'} if $r;
87 die "Run $r->subprocess_env; before calling fetch()"
88 if $MOD_PERL and !exists $ENV{REQUEST_METHOD};
90 return $ENV{HTTP_COOKIE} || $ENV{COOKIE};
95 my ($self,$raw_cookie) = @_;
98 my @pairs = split("[;,] ?",$raw_cookie);
101 my($key,$value) = split("=",$_,2);
103 # Some foreign cookies are not in name=value format, so ignore
105 next if !defined($value);
108 @values = map unescape($_),split(/[&;]/,$value.'&dmy');
111 $key = unescape($key);
112 # A bug in Netscape can cause several cookies with same name to
113 # appear. The FIRST one in HTTP_COOKIE is the most recent version.
114 $results{$key} ||= $self->new(-name=>$key,-value=>\@values);
116 return \%results unless wantarray;
122 $class = ref($class) if ref($class);
123 # Ignore mod_perl request object--compatability with Apache::Cookie.
125 && eval { $_[0]->isa('Apache::Request::Req') || $_[0]->isa('Apache') };
126 my($name,$value,$path,$domain,$secure,$expires,$httponly) =
127 rearrange([ 'NAME', ['VALUE','VALUES'], qw/ PATH DOMAIN SECURE EXPIRES
130 # Pull out our parameters.
133 if (ref($value) eq 'ARRAY') {
135 } elsif (ref($value) eq 'HASH') {
147 # IE requires the path and domain to be present for some reason.
149 # however, this breaks networks which use host tables without fully qualified
150 # names, so we comment it out.
151 # $domain = CGI::virtual_host() unless defined $domain;
153 $self->path($path) if defined $path;
154 $self->domain($domain) if defined $domain;
155 $self->secure($secure) if defined $secure;
156 $self->expires($expires) if defined $expires;
157 $self->httponly($httponly) if defined $httponly;
158 # $self->max_age($expires) if defined $expires;
164 return "" unless $self->name;
166 my(@constant_values,$domain,$path,$expires,$max_age,$secure,$httponly);
168 push(@constant_values,"domain=$domain") if $domain = $self->domain;
169 push(@constant_values,"path=$path") if $path = $self->path;
170 push(@constant_values,"expires=$expires") if $expires = $self->expires;
171 push(@constant_values,"max-age=$max_age") if $max_age = $self->max_age;
172 push(@constant_values,"secure") if $secure = $self->secure;
173 push(@constant_values,"HttpOnly") if $httponly = $self->httponly;
175 my($key) = escape($self->name);
176 my($cookie) = join("=",(defined $key ? $key : ''),join("&",map escape(defined $_ ? $_ : ''),$self->value));
177 return join("; ",$cookie,@constant_values);
183 return "$self" cmp $value;
191 ? Apache2::RequestUtil->request()
195 $r->headers_out->add('Set-Cookie' => $self->as_string);
197 print CGI::header(-cookie => $self);
206 $self->{'name'} = $name if defined $name;
207 return $self->{'name'};
213 if (defined $value) {
216 if (ref($value) eq 'ARRAY') {
218 } elsif (ref($value) eq 'HASH') {
224 $self->{'value'} = [@values];
226 return wantarray ? @{$self->{'value'}} : $self->{'value'}->[0]
232 $self->{'domain'} = lc $domain if defined $domain;
233 return $self->{'domain'};
239 $self->{'secure'} = $secure if defined $secure;
240 return $self->{'secure'};
246 $self->{'expires'} = CGI::Util::expires($expires,'cookie') if defined $expires;
247 return $self->{'expires'};
253 $self->{'max-age'} = CGI::Util::expire_calc($expires)-time() if defined $expires;
254 return $self->{'max-age'};
260 $self->{'path'} = $path if defined $path;
261 return $self->{'path'};
265 sub httponly { # HttpOnly
267 my $httponly = shift;
268 $self->{'httponly'} = $httponly if defined $httponly;
269 return $self->{'httponly'};
276 CGI::Cookie - Interface to Netscape Cookies
280 use CGI qw/:standard/;
283 # Create new cookies and send them
284 $cookie1 = new CGI::Cookie(-name=>'ID',-value=>123456);
285 $cookie2 = new CGI::Cookie(-name=>'preferences',
286 -value=>{ font => Helvetica,
289 print header(-cookie=>[$cookie1,$cookie2]);
291 # fetch existing cookies
292 %cookies = fetch CGI::Cookie;
293 $id = $cookies{'ID'}->value;
295 # create cookies returned from an external source
296 %cookies = parse CGI::Cookie($ENV{COOKIE});
300 CGI::Cookie is an interface to Netscape (HTTP/1.1) cookies, an
301 innovation that allows Web servers to store persistent information on
302 the browser's side of the connection. Although CGI::Cookie is
303 intended to be used in conjunction with CGI.pm (and is in fact used by
304 it internally), you can use this module independently.
306 For full information on cookies see
308 http://www.ics.uci.edu/pub/ietf/http/rfc2109.txt
310 =head1 USING CGI::Cookie
312 CGI::Cookie is object oriented. Each cookie object has a name and a
313 value. The name is any scalar value. The value is any scalar or
314 array value (associative arrays are also allowed). Cookies also have
315 several optional attributes, including:
319 =item B<1. expiration date>
321 The expiration date tells the browser how long to hang on to the
322 cookie. If the cookie specifies an expiration date in the future, the
323 browser will store the cookie information in a disk file and return it
324 to the server every time the user reconnects (until the expiration
325 date is reached). If the cookie species an expiration date in the
326 past, the browser will remove the cookie from the disk file. If the
327 expiration date is not specified, the cookie will persist only until
328 the user quits the browser.
332 This is a partial or complete domain name for which the cookie is
333 valid. The browser will return the cookie to any host that matches
334 the partial domain name. For example, if you specify a domain name
335 of ".capricorn.com", then Netscape will return the cookie to
336 Web servers running on any of the machines "www.capricorn.com",
337 "ftp.capricorn.com", "feckless.capricorn.com", etc. Domain names
338 must contain at least two periods to prevent attempts to match
339 on top level domains like ".edu". If no domain is specified, then
340 the browser will only return the cookie to servers on the host the
341 cookie originated from.
345 If you provide a cookie path attribute, the browser will check it
346 against your script's URL before returning the cookie. For example,
347 if you specify the path "/cgi-bin", then the cookie will be returned
348 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl", and
349 "/cgi-bin/customer_service/complain.pl", but not to the script
350 "/cgi-private/site_admin.pl". By default, the path is set to "/", so
351 that all scripts at your site will receive the cookie.
353 =item B<4. secure flag>
355 If the "secure" attribute is set, the cookie will only be sent to your
356 script if the CGI request is occurring on a secure channel, such as SSL.
358 =item B<4. httponly flag>
360 If the "httponly" attribute is set, the cookie will only be accessible
361 through HTTP Requests. This cookie will be inaccessible via JavaScript
362 (to prevent XSS attacks).
364 But, currently this feature only used and recognised by
365 MS Internet Explorer 6 Service Pack 1 and later.
367 See this URL for more information:
369 L<http://msdn.microsoft.com/en-us/library/ms533046%28VS.85%29.aspx>
373 =head2 Creating New Cookies
375 my $c = new CGI::Cookie(-name => 'foo',
378 -domain => '.capricorn.com',
379 -path => '/cgi-bin/database',
383 Create cookies from scratch with the B<new> method. The B<-name> and
384 B<-value> parameters are required. The name must be a scalar value.
385 The value can be a scalar, an array reference, or a hash reference.
386 (At some point in the future cookies will support one of the Perl
387 object serialization protocols for full generality).
389 B<-expires> accepts any of the relative or absolute date formats
390 recognized by CGI.pm, for example "+3M" for three months in the
391 future. See CGI.pm's documentation for details.
393 B<-domain> points to a domain name or to a fully qualified host name.
394 If not specified, the cookie will be returned only to the Web server
397 B<-path> points to a partial URL on the current server. The cookie
398 will be returned to all URLs beginning with the specified path. If
399 not specified, it defaults to '/', which returns the cookie to all
402 B<-secure> if set to a true value instructs the browser to return the
403 cookie only when a cryptographic protocol is in use.
405 B<-httponly> if set to a true value, the cookie will not be accessible
408 For compatibility with Apache::Cookie, you may optionally pass in
409 a mod_perl request object as the first argument to C<new()>. It will
412 my $c = new CGI::Cookie($r,
414 -value => ['bar','baz']);
416 =head2 Sending the Cookie to the Browser
418 The simplest way to send a cookie to the browser is by calling the bake()
423 Under mod_perl, pass in an Apache request object:
427 If you want to set the cookie yourself, Within a CGI script you can send
428 a cookie to the browser by creating one or more Set-Cookie: fields in the
429 HTTP header. Here is a typical sequence:
431 my $c = new CGI::Cookie(-name => 'foo',
432 -value => ['bar','baz'],
435 print "Set-Cookie: $c\n";
436 print "Content-Type: text/html\n\n";
438 To send more than one cookie, create several Set-Cookie: fields.
440 If you are using CGI.pm, you send cookies by providing a -cookie
441 argument to the header() method:
443 print header(-cookie=>$c);
445 Mod_perl users can set cookies using the request object's header_out()
448 $r->headers_out->set('Set-Cookie' => $c);
450 Internally, Cookie overloads the "" operator to call its as_string()
451 method when incorporated into the HTTP header. as_string() turns the
452 Cookie's internal representation into an RFC-compliant text
453 representation. You may call as_string() yourself if you prefer:
455 print "Set-Cookie: ",$c->as_string,"\n";
457 =head2 Recovering Previous Cookies
459 %cookies = fetch CGI::Cookie;
461 B<fetch> returns an associative array consisting of all cookies
462 returned by the browser. The keys of the array are the cookie names. You
463 can iterate through the cookies this way:
465 %cookies = fetch CGI::Cookie;
466 foreach (keys %cookies) {
467 do_something($cookies{$_});
470 In a scalar context, fetch() returns a hash reference, which may be more
471 efficient if you are manipulating multiple cookies.
473 CGI.pm uses the URL escaping methods to save and restore reserved characters
474 in its cookies. If you are trying to retrieve a cookie set by a foreign server,
475 this escaping method may trip you up. Use raw_fetch() instead, which has the
476 same semantics as fetch(), but performs no unescaping.
478 You may also retrieve cookies that were stored in some external
479 form using the parse() class method:
481 $COOKIES = `cat /usr/tmp/Cookie_stash`;
482 %cookies = parse CGI::Cookie($COOKIES);
484 If you are in a mod_perl environment, you can save some overhead by
485 passing the request object to fetch() like this:
487 CGI::Cookie->fetch($r);
489 =head2 Manipulating Cookies
491 Cookie objects have a series of accessor methods to get and set cookie
492 attributes. Each accessor has a similar syntax. Called without
493 arguments, the accessor returns the current value of the attribute.
494 Called with an argument, the accessor changes the attribute and
495 returns its new value.
501 Get or set the cookie's name. Example:
504 $new_name = $c->name('fred');
508 Get or set the cookie's value. Example:
511 @new_value = $c->value(['a','b','c','d']);
513 B<value()> is context sensitive. In a list context it will return
514 the current value of the cookie as an array. In a scalar context it
515 will return the B<first> value of a multivalued cookie.
519 Get or set the cookie's domain.
523 Get or set the cookie's path.
527 Get or set the cookie's expiration time.
532 =head1 AUTHOR INFORMATION
534 Copyright 1997-1998, Lincoln D. Stein. All rights reserved.
536 This library is free software; you can redistribute it and/or modify
537 it under the same terms as Perl itself.
539 Address bug reports and comments to: lstein@cshl.org
543 This section intentionally left blank.