4 # See the bottom of this file for the POD documentation. Search for the
7 # You can run this file through either pod2man or pod2html to produce pretty
8 # documentation in manual or html file format (these utilities are part of the
9 # Perl 5 distribution).
11 # Copyright 1995-1998 Lincoln D. Stein. All rights reserved.
12 # It may be used and modified freely, but I do request that this copyright
13 # notice remain attached to the file. You may modify this module as you
14 # wish, but if you redistribute a modified version, please attach a note
15 # listing the modifications you have made.
17 # The most recent version and complete docs are available at:
18 # http://stein.cshl.org/WWW/software/CGI/
20 $CGI::revision = '$Id: CGI.pm,v 1.18 1999/06/09 14:52:45 lstein Exp $';
23 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
24 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
25 # $TempFile::TMPDIRECTORY = '/usr/tmp';
27 # >>>>> Here are some globals that you might want to adjust <<<<<<
28 sub initialize_globals {
29 # Set this to 1 to enable copious autoloader debugging messages
32 # Change this to the preferred DTD to print in start_html()
33 # or use default_dtd('text of DTD to use');
34 $DEFAULT_DTD = '-//IETF//DTD HTML//EN';
36 # Set this to 1 to enable NPH scripts
40 # 3) print header(-nph=>1)
43 # Set this to 1 to disable debugging from the
47 # Set this to 1 to make the temporary files created
48 # during file uploads safe from prying eyes
50 # 1) use CGI qw(:private_tempfiles)
51 # 2) $CGI::private_tempfiles(1);
52 $PRIVATE_TEMPFILES = 0;
54 # Set this to a positive value to limit the size of a POSTing
55 # to a certain number of bytes:
58 # Change this to 1 to disable uploads entirely:
61 # Automatically determined -- don't change
64 # Change this to 1 to suppress redundant HTTP headers
67 # separate the name=value pairs by semicolons rather than ampersands
68 $USE_PARAM_SEMICOLONS = 0;
70 # Other globals that you shouldn't worry about.
76 # prevent complaints by mod_perl
80 # ------------------ START OF THE LIBRARY ------------
85 # FIGURE OUT THE OS WE'RE RUNNING UNDER
86 # Some systems support the $^O variable. If not
87 # available then require() the Config library
91 $OS = $Config::Config{'osname'};
96 } elsif ($OS=~/vms/i) {
98 } elsif ($OS=~/dos/i) {
100 } elsif ($OS=~/^MacOS$/i) {
102 } elsif ($OS=~/os2/i) {
108 # Some OS logic. Binary mode enabled on DOS, NT and VMS
109 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin)/;
111 # This is the default class for the CGI object to use when all else fails.
112 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
114 # This is where to look for autoloaded routines.
115 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
117 # The path separator is a slash, backslash or semicolon, depending
120 UNIX=>'/', OS2=>'\\', WINDOWS=>'\\', DOS=>'\\', MACINTOSH=>':', VMS=>'/'
123 # This no longer seems to be necessary
124 # Turn on NPH scripts by default when running under IIS server!
125 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
126 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
128 # Turn on special checking for Doug MacEachern's modperl
129 if (exists $ENV{'GATEWAY_INTERFACE'}
131 ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//))
136 # Turn on special checking for ActiveState's PerlEx
137 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
139 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
140 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
141 # and sometimes CR). The most popular VMS web server
142 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
143 # use ASCII, so \015\012 means something different. I find this all
145 $EBCDIC = "\t" ne "\011";
156 0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 21, 11, 12, 13, 14, 15,
157 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31,
158 64, 90,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97,
159 240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111,
160 124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214,
161 215,216,217,226,227,228,229,230,231,232,233,173,224,189, 95,109,
162 121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150,
163 151,152,153,162,163,164,165,166,167,168,169,192, 79,208,161, 7,
164 32, 33, 34, 35, 36, 37, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27,
165 48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62,255,
166 65,170, 74,177,159,178,106,181,187,180,154,138,176,202,175,188,
167 144,143,234,250,190,160,182,179,157,218,155,139,183,184,185,171,
168 100,101, 98,102, 99,103,158,104,116,113,114,115,120,117,118,119,
169 172,105,237,238,235,239,236,191,128,253,254,251,252,186,174, 89,
170 68, 69, 66, 70, 67, 71,156, 72, 84, 81, 82, 83, 88, 85, 86, 87,
171 140, 73,205,206,203,207,204,225,112,221,222,219,220,141,142,223
175 if ($needs_binmode) {
176 $CGI::DefaultClass->binmode(main::STDOUT);
177 $CGI::DefaultClass->binmode(main::STDIN);
178 $CGI::DefaultClass->binmode(main::STDERR);
182 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
183 tt u i b blockquote pre img a address cite samp dfn html head
184 base body Link nextid title meta kbd start_html end_html
185 input Select option comment/],
186 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
187 embed basefont style span layer ilayer font frameset frame script small big/],
188 ':netscape'=>[qw/blink fontsize center/],
189 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
190 submit reset defaults radio_group popup_menu button autoEscape
191 scrolling_list image_button start_form end_form startform endform
192 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
193 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
194 raw_cookie request_method query_string Accept user_agent remote_host content_type
195 remote_addr referer server_name server_software server_port server_protocol
196 virtual_host remote_ident auth_type http use_named_parameters
197 save_parameters restore_parameters param_fetch
198 remote_user user_name header redirect import_names put
199 Delete Delete_all url_param cgi_error/],
200 ':ssl' => [qw/https/],
201 ':imagemap' => [qw/Area Map/],
202 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
203 ':html' => [qw/:html2 :html3 :netscape/],
204 ':standard' => [qw/:html2 :html3 :form :cgi/],
205 ':push' => [qw/multipart_init multipart_start multipart_end/],
206 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal/]
209 # to import symbols into caller
213 # This causes modules to clash.
217 $self->_setup_symbols(@_);
218 my ($callpack, $callfile, $callline) = caller;
220 # To allow overriding, search through the packages
221 # Till we find one in which the correct subroutine is defined.
222 my @packages = ($self,@{"$self\:\:ISA"});
223 foreach $sym (keys %EXPORT) {
225 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
226 foreach $pck (@packages) {
227 if (defined(&{"$pck\:\:$sym"})) {
232 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
238 $pack->_setup_symbols('-compile',@_);
243 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
245 return ($tag) unless $EXPORT_TAGS{$tag};
246 foreach (@{$EXPORT_TAGS{$tag}}) {
247 push(@r,&expand_tags($_));
253 # The new routine. This will check the current environment
254 # for an existing query string, and initialize itself, if so.
257 my($class,$initializer) = @_;
259 bless $self,ref $class || $class || $DefaultClass;
261 Apache->request->register_cleanup(\&CGI::_reset_globals);
264 $self->_reset_globals if $PERLEX;
265 $self->init($initializer);
269 # We provide a DESTROY method so that the autoloader
270 # doesn't bother trying to find it.
274 # Returns the value(s)of a named parameter.
275 # If invoked in a list context, returns the
276 # entire list. Otherwise returns the first
277 # member of the list.
278 # If name is not provided, return a list of all
279 # the known parameters names available.
280 # If more than one argument is provided, the
281 # second and subsequent arguments are used to
282 # set the value of the parameter.
285 my($self,@p) = self_or_default(@_);
286 return $self->all_parameters unless @p;
287 my($name,$value,@other);
289 # For compatibility between old calling style and use_named_parameters() style,
290 # we have to special case for a single parameter present.
292 ($name,$value,@other) = $self->rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
295 if (substr($p[0],0,1) eq '-' || $self->use_named_parameters) {
296 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
298 foreach ($value,@other) {
299 push(@values,$_) if defined($_);
302 # If values is provided, then we set it.
304 $self->add_parameter($name);
305 $self->{$name}=[@values];
311 return unless defined($name) && $self->{$name};
312 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
315 sub self_or_default {
316 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
317 unless (defined($_[0]) &&
318 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
320 $Q = $CGI::DefaultClass->new unless defined($Q);
327 local $^W=0; # prevent a warning
328 if (defined($_[0]) &&
329 (substr(ref($_[0]),0,3) eq 'CGI'
330 || UNIVERSAL::isa($_[0],'CGI'))) {
333 return ($DefaultClass,@_);
337 ########################################
338 # THESE METHODS ARE MORE OR LESS PRIVATE
339 # GO TO THE __DATA__ SECTION TO SEE MORE
341 ########################################
343 # Initialize the query object from the environment.
344 # If a parameter list is found, this object will be set
345 # to an associative array in which parameter names are keys
346 # and the values are stored as lists
347 # If a keyword list is found, this method creates a bogus
348 # parameter list with the single parameter 'keywords'.
351 my($self,$initializer) = @_;
352 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
355 # if we get called more than once, we want to initialize
356 # ourselves from the original query (which may be gone
357 # if it was read from STDIN originally.)
358 if (@QUERY_PARAM && !defined($initializer)) {
359 foreach (@QUERY_PARAM) {
360 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
365 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
366 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
368 $fh = to_filehandle($initializer) if $initializer;
372 # avoid unreasonably large postings
373 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
374 $self->cgi_error("413 Request entity too large");
378 # Process multipart postings, but only if the initializer is
381 && defined($ENV{'CONTENT_TYPE'})
382 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
383 && !defined($initializer)
385 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
386 $self->read_multipart($boundary,$content_length);
390 # If initializer is defined, then read parameters
392 if (defined($initializer)) {
393 if (UNIVERSAL::isa($initializer,'CGI')) {
394 $query_string = $initializer->query_string;
397 if (ref($initializer) && ref($initializer) eq 'HASH') {
398 foreach (keys %$initializer) {
399 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
404 if (defined($fh) && ($fh ne '')) {
410 # massage back into standard format
411 if ("@lines" =~ /=/) {
412 $query_string=join("&",@lines);
414 $query_string=join("+",@lines);
419 # last chance -- treat it as a string
420 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
421 $query_string = $initializer;
426 # If method is GET or HEAD, fetch the query from
428 if ($meth=~/^(GET|HEAD)$/) {
430 $query_string = Apache->request->args;
432 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
437 if ($meth eq 'POST') {
438 $self->read_from_client(\*STDIN,\$query_string,$content_length,0)
439 if $content_length > 0;
440 # Some people want to have their cake and eat it too!
441 # Uncomment this line to have the contents of the query string
442 # APPENDED to the POST data.
443 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
447 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
448 # Check the command line and then the standard input for data.
449 # We use the shellwords package in order to behave the way that
450 # UN*X programmers expect.
451 $query_string = read_from_cmdline() unless $NO_DEBUG;
454 # We now have the query string in hand. We do slightly
455 # different things for keyword lists and parameter lists.
456 if ($query_string ne '') {
457 if ($query_string =~ /=/) {
458 $self->parse_params($query_string);
460 $self->add_parameter('keywords');
461 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
465 # Special case. Erase everything if there is a field named
467 if ($self->param('.defaults')) {
471 # Associative array containing our defined fieldnames
472 $self->{'.fieldnames'} = {};
473 foreach ($self->param('.cgifields')) {
474 $self->{'.fieldnames'}->{$_}++;
477 # Clear out our default submission button flag if present
478 $self->delete('.submit');
479 $self->delete('.cgifields');
480 $self->save_request unless $initializer;
483 # FUNCTIONS TO OVERRIDE:
484 # Turn a string into a filehandle
487 return undef unless $thingy;
488 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
489 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
492 while (my $package = caller($caller++)) {
493 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
494 return $tmp if defined(fileno($tmp));
500 # send output to the browser
502 my($self,@p) = self_or_default(@_);
506 # print to standard output (for overriding in mod_perl)
512 # get/set last cgi_error
514 my ($self,$err) = self_or_default(@_);
515 $self->{'.cgi_error'} = $err if defined $err;
516 return $self->{'.cgi_error'};
519 # unescape URL-encoded data
521 shift() if ref($_[0]) || $_[0] eq $DefaultClass;
522 my $todecode = shift;
523 return undef unless defined($todecode);
524 $todecode =~ tr/+/ /; # pluses become spaces
526 $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",$A2E[hex($1)])/ge;
528 $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
535 shift() if ref($_[0]) || $_[0] eq $DefaultClass;
536 my $toencode = shift;
537 return undef unless defined($toencode);
539 $toencode=~s/([^a-zA-Z0-9_.+-])/uc sprintf("%%%02x",ord($1))/eg;
545 # We're going to play with the package globals now so that if we get called
546 # again, we initialize ourselves in exactly the same way. This allows
547 # us to have several of these objects.
548 @QUERY_PARAM = $self->param; # save list of parameters
549 foreach (@QUERY_PARAM) {
550 $QUERY_PARAM{$_}=$self->{$_};
555 my($self,$tosplit) = @_;
556 my(@pairs) = split(/[&;]/,$tosplit);
559 ($param,$value) = split('=',$_,2);
560 $param = unescape($param);
561 $value = unescape($value);
562 $self->add_parameter($param);
563 push (@{$self->{$param}},$value);
569 push (@{$self->{'.parameters'}},$param)
570 unless defined($self->{$param});
575 return () unless defined($self) && $self->{'.parameters'};
576 return () unless @{$self->{'.parameters'}};
577 return @{$self->{'.parameters'}};
580 # put a filehandle into binary mode (DOS)
582 CORE::binmode($_[1]);
586 my ($self,$tagname) = @_;
590 # (!ref(\$_[0]) && \$_[0] eq \$CGI::DefaultClass) ||
592 (substr(ref(\$_[0]),0,3) eq 'CGI' ||
593 UNIVERSAL::isa(\$_[0],'CGI')));
596 if (ref(\$_[0]) && ref(\$_[0]) eq 'HASH') {
597 my(\@attr) = make_attributes( '',shift() );
598 \$attr = " \@attr" if \@attr;
601 if ($tagname=~/start_(\w+)/i) {
602 $func .= qq! return "<\U$1\E\$attr>";} !;
603 } elsif ($tagname=~/end_(\w+)/i) {
604 $func .= qq! return "<\U/$1\E>"; } !;
607 my(\$tag,\$untag) = ("\U<$tagname\E\$attr>","\U</$tagname>\E");
608 return \$tag unless \@_;
609 my \@result = map { "\$tag\$_\$untag" } (ref(\$_[0]) eq 'ARRAY') ? \@{\$_[0]} : "\@_";
617 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
618 my $func = &_compile;
623 # Smart rearrangement of parameters to allow named parameter
624 # calling. We do the rearangement if:
625 # 1. The first parameter begins with a -
626 # 2. The use_named_parameters() method returns true
628 my($self,$order,@param) = @_;
629 return () unless @param;
631 if (ref($param[0]) eq 'HASH') {
632 @param = %{$param[0]};
635 unless (defined($param[0]) && substr($param[0],0,1) eq '-')
636 || $self->use_named_parameters;
639 # map parameters into positional indices
643 foreach (ref($_) eq 'ARRAY' ? @$_ : $_) { $pos{$_} = $i; }
647 my (@result,%leftover);
648 $#result = $#$order; # preextend
650 my $key = uc(shift(@param));
652 if (exists $pos{$key}) {
653 $result[$pos{$key}] = shift(@param);
655 $leftover{$key} = shift(@param);
659 push (@result,$self->make_attributes(\%leftover)) if %leftover;
664 my($func) = $AUTOLOAD;
665 my($pack,$func_name);
667 local($1,$2); # this fixes an obscure variable suicide problem.
668 $func=~/(.+)::([^:]+)$/;
669 ($pack,$func_name) = ($1,$2);
670 $pack=~s/::SUPER$//; # fix another obscure problem
671 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
672 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
674 my($sub) = \%{"$pack\:\:SUBS"};
676 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
677 eval "package $pack; $$auto";
679 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
681 my($code) = $sub->{$func_name};
683 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
685 (my $base = $func_name) =~ s/^(start_|end_)//i;
686 if ($EXPORT{':any'} ||
689 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
690 && $EXPORT_OK{$base}) {
691 $code = $CGI::DefaultClass->_make_tag_func($func_name);
694 die "Undefined subroutine $AUTOLOAD\n" unless $code;
695 eval "package $pack; $code";
701 CORE::delete($sub->{$func_name}); #free storage
702 return "$pack\:\:$func_name";
705 sub _reset_globals { initialize_globals(); }
711 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
712 $NPH++, next if /^[:-]nph$/;
713 $NO_DEBUG++, next if /^[:-]no_?[Dd]ebug$/;
714 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
715 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
716 $EXPORT{$_}++, next if /^[:-]any$/;
717 $compile++, next if /^[:-]compile$/;
719 # This is probably extremely evil code -- to be deleted some day.
720 if (/^[-]autoload$/) {
721 my($pkg) = caller(1);
722 *{"${pkg}::AUTOLOAD"} = sub {
723 my($routine) = $AUTOLOAD;
724 $routine =~ s/^.*::/CGI::/;
730 foreach (&expand_tags($_)) {
731 tr/a-zA-Z0-9_//cd; # don't allow weird function names
735 _compile_all(keys %EXPORT) if $compile;
738 ###############################################################################
739 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
740 ###############################################################################
741 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
742 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
746 'URL_ENCODED'=> <<'END_OF_FUNC',
747 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
750 'MULTIPART' => <<'END_OF_FUNC',
751 sub MULTIPART { 'multipart/form-data'; }
754 'SERVER_PUSH' => <<'END_OF_FUNC',
755 sub SERVER_PUSH { 'multipart/x-mixed-replace; boundary="' . shift() . '"'; }
758 'use_named_parameters' => <<'END_OF_FUNC',
759 #### Method: use_named_parameters
760 # Force CGI.pm to use named parameter-style method calls
761 # rather than positional parameters. The same effect
762 # will happen automatically if the first parameter
764 sub use_named_parameters {
765 my($self,$use_named) = self_or_default(@_);
766 return $self->{'.named'} unless defined ($use_named);
768 # stupidity to avoid annoying warnings
769 return $self->{'.named'}=$use_named;
773 'new_MultipartBuffer' => <<'END_OF_FUNC',
774 # Create a new multipart buffer
775 sub new_MultipartBuffer {
776 my($self,$boundary,$length,$filehandle) = @_;
777 return MultipartBuffer->new($self,$boundary,$length,$filehandle);
781 'read_from_client' => <<'END_OF_FUNC',
782 # Read data from a file handle
783 sub read_from_client {
784 my($self, $fh, $buff, $len, $offset) = @_;
785 local $^W=0; # prevent a warning
786 return undef unless defined($fh);
787 return read($fh, $$buff, $len, $offset);
791 'delete' => <<'END_OF_FUNC',
793 # Deletes the named parameter entirely.
796 my($self,$name) = self_or_default(@_);
797 CORE::delete $self->{$name};
798 CORE::delete $self->{'.fieldnames'}->{$name};
799 @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
800 return wantarray ? () : undef;
804 #### Method: import_names
805 # Import all parameters into the given namespace.
806 # Assumes namespace 'Q' if not specified
808 'import_names' => <<'END_OF_FUNC',
810 my($self,$namespace,$delete) = self_or_default(@_);
811 $namespace = 'Q' unless defined($namespace);
812 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
813 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
814 # can anyone find an easier way to do this?
815 foreach (keys %{"${namespace}::"}) {
816 local *symbol = "${namespace}::${_}";
822 my($param,@value,$var);
823 foreach $param ($self->param) {
824 # protect against silly names
825 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
826 $var =~ s/^(?=\d)/_/;
827 local *symbol = "${namespace}::$var";
828 @value = $self->param($param);
835 #### Method: keywords
836 # Keywords acts a bit differently. Calling it in a list context
837 # returns the list of keywords.
838 # Calling it in a scalar context gives you the size of the list.
840 'keywords' => <<'END_OF_FUNC',
842 my($self,@values) = self_or_default(@_);
843 # If values is provided, then we set it.
844 $self->{'keywords'}=[@values] if @values;
845 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
850 # These are some tie() interfaces for compatibility
851 # with Steve Brenner's cgi-lib.pl routines
852 'Vars' => <<'END_OF_FUNC',
856 return %in if wantarray;
861 # These are some tie() interfaces for compatibility
862 # with Steve Brenner's cgi-lib.pl routines
863 'ReadParse' => <<'END_OF_FUNC',
873 return scalar(keys %in);
877 'PrintHeader' => <<'END_OF_FUNC',
879 my($self) = self_or_default(@_);
880 return $self->header();
884 'HtmlTop' => <<'END_OF_FUNC',
886 my($self,@p) = self_or_default(@_);
887 return $self->start_html(@p);
891 'HtmlBot' => <<'END_OF_FUNC',
893 my($self,@p) = self_or_default(@_);
894 return $self->end_html(@p);
898 'SplitParam' => <<'END_OF_FUNC',
901 my (@params) = split ("\0", $param);
902 return (wantarray ? @params : $params[0]);
906 'MethGet' => <<'END_OF_FUNC',
908 return request_method() eq 'GET';
912 'MethPost' => <<'END_OF_FUNC',
914 return request_method() eq 'POST';
918 'TIEHASH' => <<'END_OF_FUNC',
920 return $Q || new CGI;
924 'STORE' => <<'END_OF_FUNC',
926 $_[0]->param($_[1],split("\0",$_[2]));
930 'FETCH' => <<'END_OF_FUNC',
932 return $_[0] if $_[1] eq 'CGI';
933 return undef unless defined $_[0]->param($_[1]);
934 return join("\0",$_[0]->param($_[1]));
938 'FIRSTKEY' => <<'END_OF_FUNC',
940 $_[0]->{'.iterator'}=0;
941 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
945 'NEXTKEY' => <<'END_OF_FUNC',
947 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
951 'EXISTS' => <<'END_OF_FUNC',
953 exists $_[0]->{$_[1]};
957 'DELETE' => <<'END_OF_FUNC',
959 $_[0]->delete($_[1]);
963 'CLEAR' => <<'END_OF_FUNC',
971 # Append a new value to an existing query
976 my($name,$value) = $self->rearrange([NAME,[VALUE,VALUES]],@p);
977 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
979 $self->add_parameter($name);
980 push(@{$self->{$name}},@values);
982 return $self->param($name);
986 #### Method: delete_all
987 # Delete all parameters
989 'delete_all' => <<'EOF',
991 my($self) = self_or_default(@_);
998 my($self,@p) = self_or_default(@_);
1003 'Delete_all' => <<'EOF',
1005 my($self,@p) = self_or_default(@_);
1006 $self->delete_all(@p);
1010 #### Method: autoescape
1011 # If you want to turn off the autoescaping features,
1012 # call this method with undef as the argument
1013 'autoEscape' => <<'END_OF_FUNC',
1015 my($self,$escape) = self_or_default(@_);
1016 $self->{'dontescape'}=!$escape;
1021 #### Method: version
1022 # Return the current version
1024 'version' => <<'END_OF_FUNC',
1030 'make_attributes' => <<'END_OF_FUNC',
1031 sub make_attributes {
1032 my($self,$attr) = @_;
1033 return () unless $attr && ref($attr) && ref($attr) eq 'HASH';
1035 foreach (keys %{$attr}) {
1037 $key=~s/^\-//; # get rid of initial - if present
1038 $key=~tr/a-z_/A-Z-/; # parameters are upper case, use dashes
1039 push(@att,defined($attr->{$_}) ? qq/$key="$attr->{$_}"/ : qq/$key/);
1045 #### Method: url_param
1046 # Return a parameter in the QUERY_STRING, regardless of
1047 # whether this was a POST or a GET
1049 'url_param' => <<'END_OF_FUNC',
1051 my ($self,@p) = self_or_default(@_);
1052 my $name = shift(@p);
1053 return undef unless exists($ENV{QUERY_STRING});
1054 unless (exists($self->{'.url_param'})) {
1055 $self->{'.url_param'}={}; # empty hash
1056 if ($ENV{QUERY_STRING} =~ /=/) {
1057 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
1060 ($param,$value) = split('=',$_,2);
1061 $param = unescape($param);
1062 $value = unescape($value);
1063 push(@{$self->{'.url_param'}->{$param}},$value);
1066 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1069 return keys %{$self->{'.url_param'}} unless defined($name);
1070 return () unless $self->{'.url_param'}->{$name};
1071 return wantarray ? @{$self->{'.url_param'}->{$name}}
1072 : $self->{'.url_param'}->{$name}->[0];
1077 # Returns a string in which all the known parameter/value
1078 # pairs are represented as nested lists, mainly for the purposes
1081 'dump' => <<'END_OF_FUNC',
1083 my($self) = self_or_default(@_);
1084 my($param,$value,@result);
1085 return '<UL></UL>' unless $self->param;
1086 push(@result,"<UL>");
1087 foreach $param ($self->param) {
1088 my($name)=$self->escapeHTML($param);
1089 push(@result,"<LI><STRONG>$param</STRONG>");
1090 push(@result,"<UL>");
1091 foreach $value ($self->param($param)) {
1092 $value = $self->escapeHTML($value);
1093 $value =~ s/\n/<BR>\n/g;
1094 push(@result,"<LI>$value");
1096 push(@result,"</UL>");
1098 push(@result,"</UL>\n");
1099 return join("\n",@result);
1103 #### Method as_string
1105 # synonym for "dump"
1107 'as_string' => <<'END_OF_FUNC',
1114 # Write values out to a filehandle in such a way that they can
1115 # be reinitialized by the filehandle form of the new() method
1117 'save' => <<'END_OF_FUNC',
1119 my($self,$filehandle) = self_or_default(@_);
1120 $filehandle = to_filehandle($filehandle);
1122 local($,) = ''; # set print field separator back to a sane value
1123 local($\) = ''; # set output line separator to a sane value
1124 foreach $param ($self->param) {
1125 my($escaped_param) = escape($param);
1127 foreach $value ($self->param($param)) {
1128 print $filehandle "$escaped_param=",escape("$value"),"\n";
1131 print $filehandle "=\n"; # end of record
1136 #### Method: save_parameters
1137 # An alias for save() that is a better name for exportation.
1138 # Only intended to be used with the function (non-OO) interface.
1140 'save_parameters' => <<'END_OF_FUNC',
1141 sub save_parameters {
1143 return save(to_filehandle($fh));
1147 #### Method: restore_parameters
1148 # A way to restore CGI parameters from an initializer.
1149 # Only intended to be used with the function (non-OO) interface.
1151 'restore_parameters' => <<'END_OF_FUNC',
1152 sub restore_parameters {
1153 $Q = $CGI::DefaultClass->new(@_);
1157 #### Method: multipart_init
1158 # Return a Content-Type: style header for server-push
1159 # This has to be NPH, and it is advisable to set $| = 1
1161 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1164 'multipart_init' => <<'END_OF_FUNC',
1165 sub multipart_init {
1166 my($self,@p) = self_or_default(@_);
1167 my($boundary,@other) = $self->rearrange([BOUNDARY],@p);
1168 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1169 $self->{'separator'} = "\n--$boundary\n";
1170 $type = SERVER_PUSH($boundary);
1171 return $self->header(
1174 (map { split "=", $_, 2 } @other),
1175 ) . $self->multipart_end;
1180 #### Method: multipart_start
1181 # Return a Content-Type: style header for server-push, start of section
1183 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1186 'multipart_start' => <<'END_OF_FUNC',
1187 sub multipart_start {
1188 my($self,@p) = self_or_default(@_);
1189 my($type,@other) = $self->rearrange([TYPE],@p);
1190 $type = $type || 'text/html';
1191 return $self->header(
1193 (map { split "=", $_, 2 } @other),
1199 #### Method: multipart_end
1200 # Return a Content-Type: style header for server-push, end of section
1202 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1205 'multipart_end' => <<'END_OF_FUNC',
1207 my($self,@p) = self_or_default(@_);
1208 return $self->{'separator'};
1214 # Return a Content-Type: style header
1217 'header' => <<'END_OF_FUNC',
1219 my($self,@p) = self_or_default(@_);
1222 return undef if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1224 my($type,$status,$cookie,$target,$expires,$nph,@other) =
1225 $self->rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1226 STATUS,[COOKIE,COOKIES],TARGET,EXPIRES,NPH],@p);
1229 # rearrange() was designed for the HTML portion, so we
1230 # need to fix it up a little.
1232 next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1233 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ": $value"/e;
1236 $type ||= 'text/html' unless defined($type);
1238 # Maybe future compatibility. Maybe not.
1239 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1240 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1242 push(@header,"Status: $status") if $status;
1243 push(@header,"Window-Target: $target") if $target;
1244 # push all the cookies -- there may be several
1246 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1248 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1249 push(@header,"Set-Cookie: $cs") if $cs ne '';
1252 # if the user indicates an expiration time, then we need
1253 # both an Expires and a Date header (so that the browser is
1255 push(@header,"Expires: " . expires($expires,'http'))
1257 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie;
1258 push(@header,"Pragma: no-cache") if $self->cache();
1259 push(@header,@other);
1260 push(@header,"Content-Type: $type") if $type ne '';
1262 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1263 if ($MOD_PERL and not $nph) {
1264 my $r = Apache->request;
1265 $r->send_cgi_header($header);
1274 # Control whether header() will produce the no-cache
1277 'cache' => <<'END_OF_FUNC',
1279 my($self,$new_value) = self_or_default(@_);
1280 $new_value = '' unless $new_value;
1281 if ($new_value ne '') {
1282 $self->{'cache'} = $new_value;
1284 return $self->{'cache'};
1289 #### Method: redirect
1290 # Return a Location: style header
1293 'redirect' => <<'END_OF_FUNC',
1295 my($self,@p) = self_or_default(@_);
1296 my($url,$target,$cookie,$nph,@other) = $self->rearrange([[LOCATION,URI,URL],TARGET,COOKIE,NPH],@p);
1297 $url = $url || $self->self_url;
1299 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1301 '-Status'=>'302 Moved',
1304 unshift(@o,'-Target'=>$target) if $target;
1305 unshift(@o,'-Cookie'=>$cookie) if $cookie;
1306 unshift(@o,'-Type'=>'');
1307 return $self->header(@o);
1312 #### Method: start_html
1313 # Canned HTML header
1316 # $title -> (optional) The title for this HTML document (-title)
1317 # $author -> (optional) e-mail address of the author (-author)
1318 # $base -> (optional) if set to true, will enter the BASE address of this document
1319 # for resolving relative references (-base)
1320 # $xbase -> (optional) alternative base at some remote location (-xbase)
1321 # $target -> (optional) target window to load all links into (-target)
1322 # $script -> (option) Javascript code (-script)
1323 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1324 # $meta -> (optional) Meta information tags
1325 # $head -> (optional) any other elements you'd like to incorporate into the <HEAD> tag
1326 # (a scalar or array ref)
1327 # $style -> (optional) reference to an external style sheet
1328 # @other -> (optional) any other named parameters you'd like to incorporate into
1331 'start_html' => <<'END_OF_FUNC',
1333 my($self,@p) = &self_or_default(@_);
1334 my($title,$author,$base,$xbase,$script,$noscript,$target,$meta,$head,$style,$dtd,@other) =
1335 $self->rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD],@p);
1337 # strangely enough, the title needs to be escaped as HTML
1338 # while the author needs to be escaped as a URL
1339 $title = $self->escapeHTML($title || 'Untitled Document');
1340 $author = $self->escape($author);
1342 $dtd = $DEFAULT_DTD unless $dtd && $dtd =~ m|^-//|;
1343 push(@result,qq(<!DOCTYPE HTML PUBLIC "$dtd">)) if $dtd;
1344 push(@result,"<HTML><HEAD><TITLE>$title</TITLE>");
1345 push(@result,"<LINK REV=MADE HREF=\"mailto:$author\">") if defined $author;
1347 if ($base || $xbase || $target) {
1348 my $href = $xbase || $self->url('-path'=>1);
1349 my $t = $target ? qq/ TARGET="$target"/ : '';
1350 push(@result,qq/<BASE HREF="$href"$t>/);
1353 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1354 foreach (keys %$meta) { push(@result,qq(<META NAME="$_" CONTENT="$meta->{$_}">)); }
1357 push(@result,ref($head) ? @$head : $head) if $head;
1359 # handle the infrequently-used -style and -script parameters
1360 push(@result,$self->_style($style)) if defined $style;
1361 push(@result,$self->_script($script)) if defined $script;
1363 # handle -noscript parameter
1364 push(@result,<<END) if $noscript;
1370 my($other) = @other ? " @other" : '';
1371 push(@result,"</HEAD><BODY$other>");
1372 return join("\n",@result);
1377 # internal method for generating a CSS style section
1379 '_style' => <<'END_OF_FUNC',
1381 my ($self,$style) = @_;
1383 my $type = 'text/css';
1385 my($src,$code,$stype,@other) =
1386 $self->rearrange([SRC,CODE,TYPE],
1387 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1388 ref($style) eq 'ARRAY' ? @$style : %$style);
1389 $type = $stype if $stype;
1390 push(@result,qq/<LINK REL="stylesheet" TYPE="$type" HREF="$src">/) if $src;
1391 push(@result,style({'type'=>$type},"<!--\n$code\n-->")) if $code;
1393 push(@result,style({'type'=>$type},"<!--\n$style\n-->"));
1400 '_script' => <<'END_OF_FUNC',
1402 my ($self,$script) = @_;
1404 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1405 foreach $script (@scripts) {
1406 my($src,$code,$language);
1407 if (ref($script)) { # script is a hash
1408 ($src,$code,$language) =
1409 $self->rearrange([SRC,CODE,LANGUAGE],
1410 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1411 ref($script) eq 'ARRAY' ? @$script : %$script);
1414 ($src,$code,$language) = ('',$script,'JavaScript');
1417 push(@satts,'src'=>$src) if $src;
1418 push(@satts,'language'=>$language || 'JavaScript');
1419 $code = "<!-- Hide script\n$code\n// End script hiding -->"
1420 if $code && $language=~/javascript/i;
1421 $code = "<!-- Hide script\n$code\n\# End script hiding -->"
1422 if $code && $language=~/perl/i;
1423 push(@result,script({@satts},$code || ''));
1429 #### Method: end_html
1430 # End an HTML document.
1431 # Trivial method for completeness. Just returns "</BODY>"
1433 'end_html' => <<'END_OF_FUNC',
1435 return "</BODY></HTML>";
1440 ################################
1441 # METHODS USED IN BUILDING FORMS
1442 ################################
1444 #### Method: isindex
1445 # Just prints out the isindex tag.
1447 # $action -> optional URL of script to run
1449 # A string containing a <ISINDEX> tag
1450 'isindex' => <<'END_OF_FUNC',
1452 my($self,@p) = self_or_default(@_);
1453 my($action,@other) = $self->rearrange([ACTION],@p);
1454 $action = qq/ACTION="$action"/ if $action;
1455 my($other) = @other ? " @other" : '';
1456 return "<ISINDEX $action$other>";
1461 #### Method: startform
1464 # $method -> optional submission method to use (GET or POST)
1465 # $action -> optional URL of script to run
1466 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1467 'startform' => <<'END_OF_FUNC',
1469 my($self,@p) = self_or_default(@_);
1471 my($method,$action,$enctype,@other) =
1472 $self->rearrange([METHOD,ACTION,ENCTYPE],@p);
1474 $method = $method || 'POST';
1475 $enctype = $enctype || &URL_ENCODED;
1476 $action = $action ? qq/ACTION="$action"/ : $method eq 'GET' ?
1477 'ACTION="'.$self->script_name.'"' : '';
1478 my($other) = @other ? " @other" : '';
1479 $self->{'.parametersToAdd'}={};
1480 return qq/<FORM METHOD="$method" $action ENCTYPE="$enctype"$other>\n/;
1485 #### Method: start_form
1486 # synonym for startform
1487 'start_form' => <<'END_OF_FUNC',
1493 'end_multipart_form' => <<'END_OF_FUNC',
1494 sub end_multipart_form {
1499 #### Method: start_multipart_form
1500 # synonym for startform
1501 'start_multipart_form' => <<'END_OF_FUNC',
1502 sub start_multipart_form {
1503 my($self,@p) = self_or_default(@_);
1504 if ($self->use_named_parameters ||
1505 (defined($param[0]) && substr($param[0],0,1) eq '-')) {
1507 $p{'-enctype'}=&MULTIPART;
1508 return $self->startform(%p);
1510 my($method,$action,@other) =
1511 $self->rearrange([METHOD,ACTION],@p);
1512 return $self->startform($method,$action,&MULTIPART,@other);
1518 #### Method: endform
1520 'endform' => <<'END_OF_FUNC',
1522 my($self,@p) = self_or_default(@_);
1523 return ($self->get_fields,"</FORM>");
1528 #### Method: end_form
1529 # synonym for endform
1530 'end_form' => <<'END_OF_FUNC',
1537 '_textfield' => <<'END_OF_FUNC',
1539 my($self,$tag,@p) = self_or_default(@_);
1540 my($name,$default,$size,$maxlength,$override,@other) =
1541 $self->rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1543 my $current = $override ? $default :
1544 (defined($self->param($name)) ? $self->param($name) : $default);
1546 $current = defined($current) ? $self->escapeHTML($current) : '';
1547 $name = defined($name) ? $self->escapeHTML($name) : '';
1548 my($s) = defined($size) ? qq/ SIZE=$size/ : '';
1549 my($m) = defined($maxlength) ? qq/ MAXLENGTH=$maxlength/ : '';
1550 my($other) = @other ? " @other" : '';
1551 # this entered at cristy's request to fix problems with file upload fields
1552 # and WebTV -- not sure it won't break stuff
1553 my($value) = $current ne '' ? qq(VALUE="$current") : '';
1554 return qq/<INPUT TYPE="$tag" NAME="$name" $value$s$m$other>/;
1558 #### Method: textfield
1560 # $name -> Name of the text field
1561 # $default -> Optional default value of the field if not
1563 # $size -> Optional width of field in characaters.
1564 # $maxlength -> Optional maximum number of characters.
1566 # A string containing a <INPUT TYPE="text"> field
1568 'textfield' => <<'END_OF_FUNC',
1570 my($self,@p) = self_or_default(@_);
1571 $self->_textfield('text',@p);
1576 #### Method: filefield
1578 # $name -> Name of the file upload field
1579 # $size -> Optional width of field in characaters.
1580 # $maxlength -> Optional maximum number of characters.
1582 # A string containing a <INPUT TYPE="text"> field
1584 'filefield' => <<'END_OF_FUNC',
1586 my($self,@p) = self_or_default(@_);
1587 $self->_textfield('file',@p);
1592 #### Method: password
1593 # Create a "secret password" entry field
1595 # $name -> Name of the field
1596 # $default -> Optional default value of the field if not
1598 # $size -> Optional width of field in characters.
1599 # $maxlength -> Optional maximum characters that can be entered.
1601 # A string containing a <INPUT TYPE="password"> field
1603 'password_field' => <<'END_OF_FUNC',
1604 sub password_field {
1605 my ($self,@p) = self_or_default(@_);
1606 $self->_textfield('password',@p);
1610 #### Method: textarea
1612 # $name -> Name of the text field
1613 # $default -> Optional default value of the field if not
1615 # $rows -> Optional number of rows in text area
1616 # $columns -> Optional number of columns in text area
1618 # A string containing a <TEXTAREA></TEXTAREA> tag
1620 'textarea' => <<'END_OF_FUNC',
1622 my($self,@p) = self_or_default(@_);
1624 my($name,$default,$rows,$cols,$override,@other) =
1625 $self->rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1627 my($current)= $override ? $default :
1628 (defined($self->param($name)) ? $self->param($name) : $default);
1630 $name = defined($name) ? $self->escapeHTML($name) : '';
1631 $current = defined($current) ? $self->escapeHTML($current) : '';
1632 my($r) = $rows ? " ROWS=$rows" : '';
1633 my($c) = $cols ? " COLS=$cols" : '';
1634 my($other) = @other ? " @other" : '';
1635 return qq{<TEXTAREA NAME="$name"$r$c$other>$current</TEXTAREA>};
1641 # Create a javascript button.
1643 # $name -> (optional) Name for the button. (-name)
1644 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1645 # $onclick -> (optional) Text of the JavaScript to run when the button is
1648 # A string containing a <INPUT TYPE="button"> tag
1650 'button' => <<'END_OF_FUNC',
1652 my($self,@p) = self_or_default(@_);
1654 my($label,$value,$script,@other) = $self->rearrange([NAME,[VALUE,LABEL],
1655 [ONCLICK,SCRIPT]],@p);
1657 $label=$self->escapeHTML($label);
1658 $value=$self->escapeHTML($value);
1659 $script=$self->escapeHTML($script);
1662 $name = qq/ NAME="$label"/ if $label;
1663 $value = $value || $label;
1665 $val = qq/ VALUE="$value"/ if $value;
1666 $script = qq/ ONCLICK="$script"/ if $script;
1667 my($other) = @other ? " @other" : '';
1668 return qq/<INPUT TYPE="button"$name$val$script$other>/;
1674 # Create a "submit query" button.
1676 # $name -> (optional) Name for the button.
1677 # $value -> (optional) Value of the button when selected (also doubles as label).
1678 # $label -> (optional) Label printed on the button(also doubles as the value).
1680 # A string containing a <INPUT TYPE="submit"> tag
1682 'submit' => <<'END_OF_FUNC',
1684 my($self,@p) = self_or_default(@_);
1686 my($label,$value,@other) = $self->rearrange([NAME,[VALUE,LABEL]],@p);
1688 $label=$self->escapeHTML($label);
1689 $value=$self->escapeHTML($value);
1691 my($name) = ' NAME=".submit"';
1692 $name = qq/ NAME="$label"/ if defined($label);
1693 $value = defined($value) ? $value : $label;
1695 $val = qq/ VALUE="$value"/ if defined($value);
1696 my($other) = @other ? " @other" : '';
1697 return qq/<INPUT TYPE="submit"$name$val$other>/;
1703 # Create a "reset" button.
1705 # $name -> (optional) Name for the button.
1707 # A string containing a <INPUT TYPE="reset"> tag
1709 'reset' => <<'END_OF_FUNC',
1711 my($self,@p) = self_or_default(@_);
1712 my($label,@other) = $self->rearrange([NAME],@p);
1713 $label=$self->escapeHTML($label);
1714 my($value) = defined($label) ? qq/ VALUE="$label"/ : '';
1715 my($other) = @other ? " @other" : '';
1716 return qq/<INPUT TYPE="reset"$value$other>/;
1721 #### Method: defaults
1722 # Create a "defaults" button.
1724 # $name -> (optional) Name for the button.
1726 # A string containing a <INPUT TYPE="submit" NAME=".defaults"> tag
1728 # Note: this button has a special meaning to the initialization script,
1729 # and tells it to ERASE the current query string so that your defaults
1732 'defaults' => <<'END_OF_FUNC',
1734 my($self,@p) = self_or_default(@_);
1736 my($label,@other) = $self->rearrange([[NAME,VALUE]],@p);
1738 $label=$self->escapeHTML($label);
1739 $label = $label || "Defaults";
1740 my($value) = qq/ VALUE="$label"/;
1741 my($other) = @other ? " @other" : '';
1742 return qq/<INPUT TYPE="submit" NAME=".defaults"$value$other>/;
1747 #### Method: comment
1748 # Create an HTML <!-- comment -->
1749 # Parameters: a string
1750 'comment' => <<'END_OF_FUNC',
1752 my($self,@p) = self_or_CGI(@_);
1753 return "<!-- @p -->";
1757 #### Method: checkbox
1758 # Create a checkbox that is not logically linked to any others.
1759 # The field value is "on" when the button is checked.
1761 # $name -> Name of the checkbox
1762 # $checked -> (optional) turned on by default if true
1763 # $value -> (optional) value of the checkbox, 'on' by default
1764 # $label -> (optional) a user-readable label printed next to the box.
1765 # Otherwise the checkbox name is used.
1767 # A string containing a <INPUT TYPE="checkbox"> field
1769 'checkbox' => <<'END_OF_FUNC',
1771 my($self,@p) = self_or_default(@_);
1773 my($name,$checked,$value,$label,$override,@other) =
1774 $self->rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1776 $value = defined $value ? $value : 'on';
1778 if (!$override && ($self->{'.fieldnames'}->{$name} ||
1779 defined $self->param($name))) {
1780 $checked = grep($_ eq $value,$self->param($name)) ? ' CHECKED' : '';
1782 $checked = $checked ? ' CHECKED' : '';
1784 my($the_label) = defined $label ? $label : $name;
1785 $name = $self->escapeHTML($name);
1786 $value = $self->escapeHTML($value);
1787 $the_label = $self->escapeHTML($the_label);
1788 my($other) = @other ? " @other" : '';
1789 $self->register_parameter($name);
1790 return qq{<INPUT TYPE="checkbox" NAME="$name" VALUE="$value"$checked$other>$the_label};
1795 #### Method: checkbox_group
1796 # Create a list of logically-linked checkboxes.
1798 # $name -> Common name for all the check boxes
1799 # $values -> A pointer to a regular array containing the
1800 # values for each checkbox in the group.
1801 # $defaults -> (optional)
1802 # 1. If a pointer to a regular array of checkbox values,
1803 # then this will be used to decide which
1804 # checkboxes to turn on by default.
1805 # 2. If a scalar, will be assumed to hold the
1806 # value of a single checkbox in the group to turn on.
1807 # $linebreak -> (optional) Set to true to place linebreaks
1808 # between the buttons.
1809 # $labels -> (optional)
1810 # A pointer to an associative array of labels to print next to each checkbox
1811 # in the form $label{'value'}="Long explanatory label".
1812 # Otherwise the provided values are used as the labels.
1814 # An ARRAY containing a series of <INPUT TYPE="checkbox"> fields
1816 'checkbox_group' => <<'END_OF_FUNC',
1817 sub checkbox_group {
1818 my($self,@p) = self_or_default(@_);
1820 my($name,$values,$defaults,$linebreak,$labels,$rows,$columns,
1821 $rowheaders,$colheaders,$override,$nolabels,@other) =
1822 $self->rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1823 LINEBREAK,LABELS,ROWS,[COLUMNS,COLS],
1824 ROWHEADERS,COLHEADERS,
1825 [OVERRIDE,FORCE],NOLABELS],@p);
1827 my($checked,$break,$result,$label);
1829 my(%checked) = $self->previous_or_default($name,$defaults,$override);
1831 $break = $linebreak ? "<BR>" : '';
1832 $name=$self->escapeHTML($name);
1834 # Create the elements
1835 my(@elements,@values);
1837 @values = $self->_set_values_and_labels($values,\$labels,$name);
1839 my($other) = @other ? " @other" : '';
1841 $checked = $checked{$_} ? ' CHECKED' : '';
1843 unless (defined($nolabels) && $nolabels) {
1845 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1846 $label = $self->escapeHTML($label);
1848 $_ = $self->escapeHTML($_);
1849 push(@elements,qq/<INPUT TYPE="checkbox" NAME="$name" VALUE="$_"$checked$other>${label}${break}/);
1851 $self->register_parameter($name);
1852 return wantarray ? @elements : join(' ',@elements)
1853 unless defined($columns) || defined($rows);
1854 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1858 # Escape HTML -- used internally
1859 'escapeHTML' => <<'END_OF_FUNC',
1861 my ($self,$toencode) = self_or_default(@_);
1862 return undef unless defined($toencode);
1863 return $toencode if ref($self) && $self->{'dontescape'};
1865 $toencode=~s/&/&/g;
1866 $toencode=~s/\"/"/g;
1867 $toencode=~s/>/>/g;
1868 $toencode=~s/</</g;
1873 # unescape HTML -- used internally
1874 'unescapeHTML' => <<'END_OF_FUNC',
1876 my $string = ref($_[0]) ? $_[1] : $_[0];
1877 return undef unless defined($string);
1878 # thanks to Randal Schwartz for the correct solution to this one
1879 $string=~ s[&(.*?);]{
1885 /^#(\d+)$/ ? chr($1) :
1886 /^#x([0-9a-f]+)$/i ? chr(hex($1)) :
1893 # Internal procedure - don't use
1894 '_tableize' => <<'END_OF_FUNC',
1896 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
1899 if (defined($columns)) {
1900 $rows = int(0.99 + @elements/$columns) unless defined($rows);
1902 if (defined($rows)) {
1903 $columns = int(0.99 + @elements/$rows) unless defined($columns);
1906 # rearrange into a pretty table
1907 $result = "<TABLE>";
1909 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
1910 $result .= "<TR>" if @$colheaders;
1911 foreach (@{$colheaders}) {
1912 $result .= "<TH>$_</TH>";
1914 for ($row=0;$row<$rows;$row++) {
1916 $result .= "<TH>$rowheaders->[$row]</TH>" if @$rowheaders;
1917 for ($column=0;$column<$columns;$column++) {
1918 $result .= "<TD>" . $elements[$column*$rows + $row] . "</TD>"
1919 if defined($elements[$column*$rows + $row]);
1923 $result .= "</TABLE>";
1929 #### Method: radio_group
1930 # Create a list of logically-linked radio buttons.
1932 # $name -> Common name for all the buttons.
1933 # $values -> A pointer to a regular array containing the
1934 # values for each button in the group.
1935 # $default -> (optional) Value of the button to turn on by default. Pass '-'
1936 # to turn _nothing_ on.
1937 # $linebreak -> (optional) Set to true to place linebreaks
1938 # between the buttons.
1939 # $labels -> (optional)
1940 # A pointer to an associative array of labels to print next to each checkbox
1941 # in the form $label{'value'}="Long explanatory label".
1942 # Otherwise the provided values are used as the labels.
1944 # An ARRAY containing a series of <INPUT TYPE="radio"> fields
1946 'radio_group' => <<'END_OF_FUNC',
1948 my($self,@p) = self_or_default(@_);
1950 my($name,$values,$default,$linebreak,$labels,
1951 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
1952 $self->rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,
1953 ROWS,[COLUMNS,COLS],
1954 ROWHEADERS,COLHEADERS,
1955 [OVERRIDE,FORCE],NOLABELS],@p);
1956 my($result,$checked);
1958 if (!$override && defined($self->param($name))) {
1959 $checked = $self->param($name);
1961 $checked = $default;
1963 my(@elements,@values);
1964 @values = $self->_set_values_and_labels($values,\$labels,$name);
1966 # If no check array is specified, check the first by default
1967 $checked = $values[0] unless defined($checked) && $checked ne '';
1968 $name=$self->escapeHTML($name);
1970 my($other) = @other ? " @other" : '';
1972 my($checkit) = $checked eq $_ ? ' CHECKED' : '';
1973 my($break) = $linebreak ? '<BR>' : '';
1975 unless (defined($nolabels) && $nolabels) {
1977 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1978 $label = $self->escapeHTML($label);
1980 $_=$self->escapeHTML($_);
1981 push(@elements,qq/<INPUT TYPE="radio" NAME="$name" VALUE="$_"$checkit$other>${label}${break}/);
1983 $self->register_parameter($name);
1984 return wantarray ? @elements : join(' ',@elements)
1985 unless defined($columns) || defined($rows);
1986 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1991 #### Method: popup_menu
1992 # Create a popup menu.
1994 # $name -> Name for all the menu
1995 # $values -> A pointer to a regular array containing the
1996 # text of each menu item.
1997 # $default -> (optional) Default item to display
1998 # $labels -> (optional)
1999 # A pointer to an associative array of labels to print next to each checkbox
2000 # in the form $label{'value'}="Long explanatory label".
2001 # Otherwise the provided values are used as the labels.
2003 # A string containing the definition of a popup menu.
2005 'popup_menu' => <<'END_OF_FUNC',
2007 my($self,@p) = self_or_default(@_);
2009 my($name,$values,$default,$labels,$override,@other) =
2010 $self->rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,[OVERRIDE,FORCE]],@p);
2011 my($result,$selected);
2013 if (!$override && defined($self->param($name))) {
2014 $selected = $self->param($name);
2016 $selected = $default;
2018 $name=$self->escapeHTML($name);
2019 my($other) = @other ? " @other" : '';
2022 @values = $self->_set_values_and_labels($values,\$labels,$name);
2024 $result = qq/<SELECT NAME="$name"$other>\n/;
2026 my($selectit) = defined($selected) ? ($selected eq $_ ? 'SELECTED' : '' ) : '';
2028 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2029 my($value) = $self->escapeHTML($_);
2030 $label=$self->escapeHTML($label);
2031 $result .= "<OPTION $selectit VALUE=\"$value\">$label\n";
2034 $result .= "</SELECT>\n";
2040 #### Method: scrolling_list
2041 # Create a scrolling list.
2043 # $name -> name for the list
2044 # $values -> A pointer to a regular array containing the
2045 # values for each option line in the list.
2046 # $defaults -> (optional)
2047 # 1. If a pointer to a regular array of options,
2048 # then this will be used to decide which
2049 # lines to turn on by default.
2050 # 2. Otherwise holds the value of the single line to turn on.
2051 # $size -> (optional) Size of the list.
2052 # $multiple -> (optional) If set, allow multiple selections.
2053 # $labels -> (optional)
2054 # A pointer to an associative array of labels to print next to each checkbox
2055 # in the form $label{'value'}="Long explanatory label".
2056 # Otherwise the provided values are used as the labels.
2058 # A string containing the definition of a scrolling list.
2060 'scrolling_list' => <<'END_OF_FUNC',
2061 sub scrolling_list {
2062 my($self,@p) = self_or_default(@_);
2063 my($name,$values,$defaults,$size,$multiple,$labels,$override,@other)
2064 = $self->rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2065 SIZE,MULTIPLE,LABELS,[OVERRIDE,FORCE]],@p);
2067 my($result,@values);
2068 @values = $self->_set_values_and_labels($values,\$labels,$name);
2070 $size = $size || scalar(@values);
2072 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2073 my($is_multiple) = $multiple ? ' MULTIPLE' : '';
2074 my($has_size) = $size ? " SIZE=$size" : '';
2075 my($other) = @other ? " @other" : '';
2077 $name=$self->escapeHTML($name);
2078 $result = qq/<SELECT NAME="$name"$has_size$is_multiple$other>\n/;
2080 my($selectit) = $selected{$_} ? 'SELECTED' : '';
2082 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2083 $label=$self->escapeHTML($label);
2084 my($value)=$self->escapeHTML($_);
2085 $result .= "<OPTION $selectit VALUE=\"$value\">$label\n";
2087 $result .= "</SELECT>\n";
2088 $self->register_parameter($name);
2096 # $name -> Name of the hidden field
2097 # @default -> (optional) Initial values of field (may be an array)
2099 # $default->[initial values of field]
2101 # A string containing a <INPUT TYPE="hidden" NAME="name" VALUE="value">
2103 'hidden' => <<'END_OF_FUNC',
2105 my($self,@p) = self_or_default(@_);
2107 # this is the one place where we departed from our standard
2108 # calling scheme, so we have to special-case (darn)
2110 my($name,$default,$override,@other) =
2111 $self->rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2113 my $do_override = 0;
2114 if ( ref($p[0]) || substr($p[0],0,1) eq '-' || $self->use_named_parameters ) {
2115 @value = ref($default) ? @{$default} : $default;
2116 $do_override = $override;
2118 foreach ($default,$override,@other) {
2119 push(@value,$_) if defined($_);
2123 # use previous values if override is not set
2124 my @prev = $self->param($name);
2125 @value = @prev if !$do_override && @prev;
2127 $name=$self->escapeHTML($name);
2129 $_=$self->escapeHTML($_);
2130 push(@result,qq/<INPUT TYPE="hidden" NAME="$name" VALUE="$_">/);
2132 return wantarray ? @result : join('',@result);
2137 #### Method: image_button
2139 # $name -> Name of the button
2140 # $src -> URL of the image source
2141 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2143 # A string containing a <INPUT TYPE="image" NAME="name" SRC="url" ALIGN="alignment">
2145 'image_button' => <<'END_OF_FUNC',
2147 my($self,@p) = self_or_default(@_);
2149 my($name,$src,$alignment,@other) =
2150 $self->rearrange([NAME,SRC,ALIGN],@p);
2152 my($align) = $alignment ? " ALIGN=\U$alignment" : '';
2153 my($other) = @other ? " @other" : '';
2154 $name=$self->escapeHTML($name);
2155 return qq/<INPUT TYPE="image" NAME="$name" SRC="$src"$align$other>/;
2160 #### Method: self_url
2161 # Returns a URL containing the current script and all its
2162 # param/value pairs arranged as a query. You can use this
2163 # to create a link that, when selected, will reinvoke the
2164 # script with all its state information preserved.
2166 'self_url' => <<'END_OF_FUNC',
2168 my($self,@p) = self_or_default(@_);
2169 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2174 # This is provided as a synonym to self_url() for people unfortunate
2175 # enough to have incorporated it into their programs already!
2176 'state' => <<'END_OF_FUNC',
2184 # Like self_url, but doesn't return the query string part of
2187 'url' => <<'END_OF_FUNC',
2189 my($self,@p) = self_or_default(@_);
2190 my ($relative,$absolute,$full,$path_info,$query) =
2191 $self->rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING']],@p);
2193 $full++ if !($relative || $absolute);
2195 my $path = $self->path_info;
2197 if (exists($ENV{REQUEST_URI})) {
2199 $script_name = $ENV{REQUEST_URI};
2200 # strip query string
2201 substr($script_name,$index) = '' if ($index = index($script_name,'?')) >= 0;
2203 substr($script_name,$index) = '' if $path and ($index = rindex($script_name,$path)) >= 0;
2205 $script_name = $self->script_name;
2209 my $protocol = $self->protocol();
2210 $url = "$protocol://";
2211 my $vh = http('host');
2215 $url .= server_name();
2216 my $port = $self->server_port;
2218 unless (lc($protocol) eq 'http' && $port == 80)
2219 || (lc($protocol) eq 'https' && $port == 443);
2221 $url .= $script_name;
2222 } elsif ($relative) {
2223 ($url) = $script_name =~ m!([^/]+)$!;
2224 } elsif ($absolute) {
2225 $url = $script_name;
2227 $url .= $path if $path_info and defined $path;
2228 $url .= "?" . $self->query_string if $query and $self->query_string;
2235 # Set or read a cookie from the specified name.
2236 # Cookie can then be passed to header().
2237 # Usual rules apply to the stickiness of -value.
2239 # -name -> name for this cookie (optional)
2240 # -value -> value of this cookie (scalar, array or hash)
2241 # -path -> paths for which this cookie is valid (optional)
2242 # -domain -> internet domain in which this cookie is valid (optional)
2243 # -secure -> if true, cookie only passed through secure channel (optional)
2244 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2246 'cookie' => <<'END_OF_FUNC',
2248 my($self,@p) = self_or_default(@_);
2249 my($name,$value,$path,$domain,$secure,$expires) =
2250 $self->rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2252 require CGI::Cookie;
2254 # if no value is supplied, then we retrieve the
2255 # value of the cookie, if any. For efficiency, we cache the parsed
2256 # cookies in our state variables.
2257 unless ( defined($value) ) {
2258 $self->{'.cookies'} = CGI::Cookie->fetch
2259 unless $self->{'.cookies'};
2261 # If no name is supplied, then retrieve the names of all our cookies.
2262 return () unless $self->{'.cookies'};
2263 return keys %{$self->{'.cookies'}} unless $name;
2264 return () unless $self->{'.cookies'}->{$name};
2265 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2268 # If we get here, we're creating a new cookie
2269 return undef unless $name; # this is an error
2272 push(@param,'-name'=>$name);
2273 push(@param,'-value'=>$value);
2274 push(@param,'-domain'=>$domain) if $domain;
2275 push(@param,'-path'=>$path) if $path;
2276 push(@param,'-expires'=>$expires) if $expires;
2277 push(@param,'-secure'=>$secure) if $secure;
2279 return new CGI::Cookie(@param);
2283 # This internal routine creates an expires time exactly some number of
2284 # hours from the current time. It incorporates modifications from
2286 'expire_calc' => <<'END_OF_FUNC',
2289 my(%mult) = ('s'=>1,
2295 # format for time can be in any of the forms...
2296 # "now" -- expire immediately
2297 # "+180s" -- in 180 seconds
2298 # "+2m" -- in 2 minutes
2299 # "+12h" -- in 12 hours
2301 # "+3M" -- in 3 months
2302 # "+2y" -- in 2 years
2303 # "-3m" -- 3 minutes ago(!)
2304 # If you don't supply one of these forms, we assume you are
2305 # specifying the date yourself
2307 if (!$time || (lc($time) eq 'now')) {
2309 } elsif ($time=~/^\d+/) {
2311 } elsif ($time=~/^([+-]?(?:\d+|\d*\.\d*))([mhdMy]?)/) {
2312 $offset = ($mult{$2} || 1)*$1;
2316 return (time+$offset);
2320 # This internal routine creates date strings suitable for use in
2321 # cookies and HTTP headers. (They differ, unfortunately.)
2322 # Thanks to Mark Fisher for this.
2323 'expires' => <<'END_OF_FUNC',
2325 my($time,$format) = @_;
2328 my(@MON)=qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
2329 my(@WDAY) = qw/Sun Mon Tue Wed Thu Fri Sat/;
2331 # pass through preformatted dates for the sake of expire_calc()
2332 $time = expire_calc($time);
2333 return $time unless $time =~ /^\d+$/;
2335 # make HTTP/cookie date string from GMT'ed time
2336 # (cookies use '-' as date separator, HTTP uses ' ')
2338 $sc = '-' if $format eq "cookie";
2339 my($sec,$min,$hour,$mday,$mon,$year,$wday) = gmtime($time);
2341 return sprintf("%s, %02d$sc%s$sc%04d %02d:%02d:%02d GMT",
2342 $WDAY[$wday],$mday,$MON[$mon],$year,$hour,$min,$sec);
2346 'parse_keywordlist' => <<'END_OF_FUNC',
2347 sub parse_keywordlist {
2348 my($self,$tosplit) = @_;
2349 $tosplit = unescape($tosplit); # unescape the keywords
2350 $tosplit=~tr/+/ /; # pluses to spaces
2351 my(@keywords) = split(/\s+/,$tosplit);
2356 'param_fetch' => <<'END_OF_FUNC',
2358 my($self,@p) = self_or_default(@_);
2359 my($name) = $self->rearrange([NAME],@p);
2360 unless (exists($self->{$name})) {
2361 $self->add_parameter($name);
2362 $self->{$name} = [];
2365 return $self->{$name};
2369 ###############################################
2370 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2371 ###############################################
2373 #### Method: path_info
2374 # Return the extra virtual path information provided
2375 # after the URL (if any)
2377 'path_info' => <<'END_OF_FUNC',
2379 my ($self,$info) = self_or_default(@_);
2380 if (defined($info)) {
2381 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2382 $self->{'.path_info'} = $info;
2383 } elsif (! defined($self->{'.path_info'}) ) {
2384 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2385 $ENV{'PATH_INFO'} : '';
2387 # hack to fix broken path info in IIS
2388 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2391 return $self->{'.path_info'};
2396 #### Method: request_method
2397 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2399 'request_method' => <<'END_OF_FUNC',
2400 sub request_method {
2401 return $ENV{'REQUEST_METHOD'};
2405 #### Method: content_type
2406 # Returns the content_type string
2408 'content_type' => <<'END_OF_FUNC',
2410 return $ENV{'CONTENT_TYPE'};
2414 #### Method: path_translated
2415 # Return the physical path information provided
2416 # by the URL (if any)
2418 'path_translated' => <<'END_OF_FUNC',
2419 sub path_translated {
2420 return $ENV{'PATH_TRANSLATED'};
2425 #### Method: query_string
2426 # Synthesize a query string from our current
2429 'query_string' => <<'END_OF_FUNC',
2431 my($self) = self_or_default(@_);
2432 my($param,$value,@pairs);
2433 foreach $param ($self->param) {
2434 my($eparam) = escape($param);
2435 foreach $value ($self->param($param)) {
2436 $value = escape($value);
2437 next unless defined $value;
2438 push(@pairs,"$eparam=$value");
2441 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2447 # Without parameters, returns an array of the
2448 # MIME types the browser accepts.
2449 # With a single parameter equal to a MIME
2450 # type, will return undef if the browser won't
2451 # accept it, 1 if the browser accepts it but
2452 # doesn't give a preference, or a floating point
2453 # value between 0.0 and 1.0 if the browser
2454 # declares a quantitative score for it.
2455 # This handles MIME type globs correctly.
2457 'Accept' => <<'END_OF_FUNC',
2459 my($self,$search) = self_or_CGI(@_);
2460 my(%prefs,$type,$pref,$pat);
2462 my(@accept) = split(',',$self->http('accept'));
2465 ($pref) = /q=(\d\.\d+|\d+)/;
2466 ($type) = m#(\S+/[^;]+)#;
2468 $prefs{$type}=$pref || 1;
2471 return keys %prefs unless $search;
2473 # if a search type is provided, we may need to
2474 # perform a pattern matching operation.
2475 # The MIME types use a glob mechanism, which
2476 # is easily translated into a perl pattern match
2478 # First return the preference for directly supported
2480 return $prefs{$search} if $prefs{$search};
2482 # Didn't get it, so try pattern matching.
2483 foreach (keys %prefs) {
2484 next unless /\*/; # not a pattern match
2485 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2486 $pat =~ s/\*/.*/g; # turn it into a pattern
2487 return $prefs{$_} if $search=~/$pat/;
2493 #### Method: user_agent
2494 # If called with no parameters, returns the user agent.
2495 # If called with one parameter, does a pattern match (case
2496 # insensitive) on the user agent.
2498 'user_agent' => <<'END_OF_FUNC',
2500 my($self,$match)=self_or_CGI(@_);
2501 return $self->http('user_agent') unless $match;
2502 return $self->http('user_agent') =~ /$match/i;
2507 #### Method: raw_cookie
2508 # Returns the magic cookies for the session.
2509 # The cookies are not parsed or altered in any way, i.e.
2510 # cookies are returned exactly as given in the HTTP
2511 # headers. If a cookie name is given, only that cookie's
2512 # value is returned, otherwise the entire raw cookie
2515 'raw_cookie' => <<'END_OF_FUNC',
2517 my($self,$key) = self_or_CGI(@_);
2519 require CGI::Cookie;
2521 if (defined($key)) {
2522 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2523 unless $self->{'.raw_cookies'};
2525 return () unless $self->{'.raw_cookies'};
2526 return () unless $self->{'.raw_cookies'}->{$key};
2527 return $self->{'.raw_cookies'}->{$key};
2529 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2533 #### Method: virtual_host
2534 # Return the name of the virtual_host, which
2535 # is not always the same as the server
2537 'virtual_host' => <<'END_OF_FUNC',
2539 my $vh = http('host') || server_name();
2540 $vh =~ s/:\d+$//; # get rid of port number
2545 #### Method: remote_host
2546 # Return the name of the remote host, or its IP
2547 # address if unavailable. If this variable isn't
2548 # defined, it returns "localhost" for debugging
2551 'remote_host' => <<'END_OF_FUNC',
2553 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2559 #### Method: remote_addr
2560 # Return the IP addr of the remote host.
2562 'remote_addr' => <<'END_OF_FUNC',
2564 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2569 #### Method: script_name
2570 # Return the partial URL to this script for
2571 # self-referencing scripts. Also see
2572 # self_url(), which returns a URL with all state information
2575 'script_name' => <<'END_OF_FUNC',
2577 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2578 # These are for debugging
2579 return "/$0" unless $0=~/^\//;
2585 #### Method: referer
2586 # Return the HTTP_REFERER: useful for generating
2589 'referer' => <<'END_OF_FUNC',
2591 my($self) = self_or_CGI(@_);
2592 return $self->http('referer');
2597 #### Method: server_name
2598 # Return the name of the server
2600 'server_name' => <<'END_OF_FUNC',
2602 return $ENV{'SERVER_NAME'} || 'localhost';
2606 #### Method: server_software
2607 # Return the name of the server software
2609 'server_software' => <<'END_OF_FUNC',
2610 sub server_software {
2611 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2615 #### Method: server_port
2616 # Return the tcp/ip port the server is running on
2618 'server_port' => <<'END_OF_FUNC',
2620 return $ENV{'SERVER_PORT'} || 80; # for debugging
2624 #### Method: server_protocol
2625 # Return the protocol (usually HTTP/1.0)
2627 'server_protocol' => <<'END_OF_FUNC',
2628 sub server_protocol {
2629 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2634 # Return the value of an HTTP variable, or
2635 # the list of variables if none provided
2637 'http' => <<'END_OF_FUNC',
2639 my ($self,$parameter) = self_or_CGI(@_);
2640 return $ENV{$parameter} if $parameter=~/^HTTP/;
2641 $parameter =~ tr/-/_/;
2642 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2644 foreach (keys %ENV) {
2645 push(@p,$_) if /^HTTP/;
2652 # Return the value of HTTPS
2654 'https' => <<'END_OF_FUNC',
2657 my ($self,$parameter) = self_or_CGI(@_);
2658 return $ENV{HTTPS} unless $parameter;
2659 return $ENV{$parameter} if $parameter=~/^HTTPS/;
2660 $parameter =~ tr/-/_/;
2661 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2663 foreach (keys %ENV) {
2664 push(@p,$_) if /^HTTPS/;
2670 #### Method: protocol
2671 # Return the protocol (http or https currently)
2673 'protocol' => <<'END_OF_FUNC',
2677 return 'https' if uc($self->https()) eq 'ON';
2678 return 'https' if $self->server_port == 443;
2679 my $prot = $self->server_protocol;
2680 my($protocol,$version) = split('/',$prot);
2681 return "\L$protocol\E";
2685 #### Method: remote_ident
2686 # Return the identity of the remote user
2687 # (but only if his host is running identd)
2689 'remote_ident' => <<'END_OF_FUNC',
2691 return $ENV{'REMOTE_IDENT'};
2696 #### Method: auth_type
2697 # Return the type of use verification/authorization in use, if any.
2699 'auth_type' => <<'END_OF_FUNC',
2701 return $ENV{'AUTH_TYPE'};
2706 #### Method: remote_user
2707 # Return the authorization name used for user
2710 'remote_user' => <<'END_OF_FUNC',
2712 return $ENV{'REMOTE_USER'};
2717 #### Method: user_name
2718 # Try to return the remote user's name by hook or by
2721 'user_name' => <<'END_OF_FUNC',
2723 my ($self) = self_or_CGI(@_);
2724 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2729 # Set or return the NPH global flag
2731 'nph' => <<'END_OF_FUNC',
2733 my ($self,$param) = self_or_CGI(@_);
2734 $CGI::NPH = $param if defined($param);
2739 #### Method: private_tempfiles
2740 # Set or return the private_tempfiles global flag
2742 'private_tempfiles' => <<'END_OF_FUNC',
2743 sub private_tempfiles {
2744 my ($self,$param) = self_or_CGI(@_);
2745 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
2746 return $CGI::PRIVATE_TEMPFILES;
2750 #### Method: default_dtd
2751 # Set or return the default_dtd global
2753 'default_dtd' => <<'END_OF_FUNC',
2755 my ($self,$param) = self_or_CGI(@_);
2756 $CGI::DEFAULT_DTD = $param if defined($param);
2757 return $CGI::DEFAULT_DTD;
2761 # -------------- really private subroutines -----------------
2762 'previous_or_default' => <<'END_OF_FUNC',
2763 sub previous_or_default {
2764 my($self,$name,$defaults,$override) = @_;
2767 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2768 defined($self->param($name)) ) ) {
2769 grep($selected{$_}++,$self->param($name));
2770 } elsif (defined($defaults) && ref($defaults) &&
2771 (ref($defaults) eq 'ARRAY')) {
2772 grep($selected{$_}++,@{$defaults});
2774 $selected{$defaults}++ if defined($defaults);
2781 'register_parameter' => <<'END_OF_FUNC',
2782 sub register_parameter {
2783 my($self,$param) = @_;
2784 $self->{'.parametersToAdd'}->{$param}++;
2788 'get_fields' => <<'END_OF_FUNC',
2791 return $self->CGI::hidden('-name'=>'.cgifields',
2792 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2797 'read_from_cmdline' => <<'END_OF_FUNC',
2798 sub read_from_cmdline {
2804 require "shellwords.pl";
2805 print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2806 chomp(@lines = <STDIN>); # remove newlines
2807 $input = join(" ",@lines);
2808 @words = &shellwords($input);
2815 if ("@words"=~/=/) {
2816 $query_string = join('&',@words);
2818 $query_string = join('+',@words);
2820 return $query_string;
2825 # subroutine: read_multipart
2827 # Read multipart data and store it into our parameters.
2828 # An interesting feature is that if any of the parts is a file, we
2829 # create a temporary file and open up a filehandle on it so that the
2830 # caller can read from it if necessary.
2832 'read_multipart' => <<'END_OF_FUNC',
2833 sub read_multipart {
2834 my($self,$boundary,$length,$filehandle) = @_;
2835 my($buffer) = $self->new_MultipartBuffer($boundary,$length,$filehandle);
2836 return unless $buffer;
2839 while (!$buffer->eof) {
2840 %header = $buffer->readHeader;
2843 $self->cgi_error("400 Bad request (malformed multipart POST)");
2847 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
2849 # Bug: Netscape doesn't escape quotation marks in file names!!!
2850 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\";]*)"?/;
2852 # add this parameter to our list
2853 $self->add_parameter($param);
2855 # If no filename specified, then just read the data and assign it
2856 # to our parameter list.
2857 unless ($filename) {
2858 my($value) = $buffer->readBody;
2859 push(@{$self->{$param}},$value);
2863 my ($tmpfile,$tmp,$filehandle);
2865 # If we get here, then we are dealing with a potentially large
2866 # uploaded form. Save the data to a temporary file, then open
2867 # the file for reading.
2869 # skip the file if uploads disabled
2870 if ($DISABLE_UPLOADS) {
2871 while (defined($data = $buffer->read)) { }
2875 # choose a relatively unpredictable tmpfile sequence number
2876 my $seqno = unpack("%16C*",join('',localtime,values %ENV));
2877 for (my $cnt=10;$cnt>0;$cnt--) {
2878 next unless $tmpfile = new TempFile($seqno);
2879 $tmp = $tmpfile->as_string;
2880 last if $filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES);
2881 $seqno += int rand(100);
2883 die "CGI open of tmpfile: $!\n" unless $filehandle;
2884 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2888 while (defined($data = $buffer->read)) {
2889 print $filehandle $data;
2892 # back up to beginning of file
2893 seek($filehandle,0,0);
2894 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2896 # Save some information about the uploaded file where we can get
2898 $self->{'.tmpfiles'}->{$filename}= {
2902 push(@{$self->{$param}},$filehandle);
2908 'upload' =><<'END_OF_FUNC',
2910 my($self,$param_name) = self_or_default(@_);
2911 my $param = $self->param($param_name);
2912 return unless $param;
2913 return unless ref($param) && fileno($param);
2918 'tmpFileName' => <<'END_OF_FUNC',
2920 my($self,$filename) = self_or_default(@_);
2921 return $self->{'.tmpfiles'}->{$filename}->{name} ?
2922 $self->{'.tmpfiles'}->{$filename}->{name}->as_string
2927 'uploadInfo' => <<'END_OF_FUNC',
2929 my($self,$filename) = self_or_default(@_);
2930 return $self->{'.tmpfiles'}->{$filename}->{info};
2934 # internal routine, don't use
2935 '_set_values_and_labels' => <<'END_OF_FUNC',
2936 sub _set_values_and_labels {
2939 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
2940 return $self->param($n) if !defined($v);
2941 return $v if !ref($v);
2942 return ref($v) eq 'HASH' ? keys %$v : @$v;
2946 '_compile_all' => <<'END_OF_FUNC',
2949 next if defined(&$_);
2950 $AUTOLOAD = "CGI::$_";
2960 #########################################################
2961 # Globals and stubs for other packages that we use.
2962 #########################################################
2964 ################### Fh -- lightweight filehandle ###############
2973 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
2975 $AUTOLOADED_ROUTINES = ''; # prevent -w error
2976 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2978 'asString' => <<'END_OF_FUNC',
2981 # get rid of package name
2982 (my $i = $$self) =~ s/^\*(\w+::)+//;
2986 # This was an extremely clever patch that allowed "use strict refs".
2987 # Unfortunately it relied on another bug that caused leaky file descriptors.
2988 # The underlying bug has been fixed, so this no longer works. However
2989 # "strict refs" still works for some reason.
2991 # return ${*{$self}{SCALAR}};
2996 'compare' => <<'END_OF_FUNC',
3000 return "$self" cmp $value;
3004 'new' => <<'END_OF_FUNC',
3006 my($pack,$name,$file,$delete) = @_;
3007 require Fcntl unless defined &Fcntl::O_RDWR;
3009 my $ref = \*{'Fh::' . quotemeta($name)};
3010 sysopen($ref,$file,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3011 unlink($file) if $delete;
3012 CORE::delete $Fh::{$FH};
3013 return bless $ref,$pack;
3017 'DESTROY' => <<'END_OF_FUNC',
3027 ######################## MultipartBuffer ####################
3028 package MultipartBuffer;
3030 # how many bytes to read at a time. We use
3031 # a 4K buffer by default.
3032 $INITIAL_FILLUNIT = 1024 * 4;
3033 $TIMEOUT = 240*60; # 4 hour timeout for big files
3034 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3037 #reuse the autoload function
3038 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3040 # avoid autoloader warnings
3043 ###############################################################################
3044 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3045 ###############################################################################
3046 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3047 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3050 'new' => <<'END_OF_FUNC',
3052 my($package,$interface,$boundary,$length,$filehandle) = @_;
3053 $FILLUNIT = $INITIAL_FILLUNIT;
3056 my($package) = caller;
3057 # force into caller's package if necessary
3058 $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
3060 $IN = "main::STDIN" unless $IN;
3062 $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
3064 # If the user types garbage into the file upload field,
3065 # then Netscape passes NOTHING to the server (not good).
3066 # We may hang on this read in that case. So we implement
3067 # a read timeout. If nothing is ready to read
3068 # by then, we return.
3070 # Netscape seems to be a little bit unreliable
3071 # about providing boundary strings.
3074 # Under the MIME spec, the boundary consists of the
3075 # characters "--" PLUS the Boundary string
3077 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3078 # the two extra hyphens. We do a special case here on the user-agent!!!!
3079 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac');
3081 } else { # otherwise we find it ourselves
3083 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3084 $boundary = <$IN>; # BUG: This won't work correctly under mod_perl
3085 $length -= length($boundary);
3086 chomp($boundary); # remove the CRLF
3087 $/ = $old; # restore old line separator
3090 my $self = {LENGTH=>$length,
3091 BOUNDARY=>$boundary,
3093 INTERFACE=>$interface,
3097 $FILLUNIT = length($boundary)
3098 if length($boundary) > $FILLUNIT;
3100 my $retval = bless $self,ref $package || $package;
3102 # Read the preamble and the topmost (boundary) line plus the CRLF.
3103 while ($self->read(0)) { }
3104 die "Malformed multipart POST\n" if $self->eof;
3110 'readHeader' => <<'END_OF_FUNC',
3117 if ($CGI::OS eq 'VMS') { # tssk, tssk: inconsistency alert!
3118 local($CRLF) = "\015\012";
3122 $self->fillBuffer($FILLUNIT);
3123 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3124 $ok++ if $self->{BUFFER} eq '';
3125 $bad++ if !$ok && $self->{LENGTH} <= 0;
3126 # this was a bad idea
3127 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3128 } until $ok || $bad;
3131 my($header) = substr($self->{BUFFER},0,$end+2);
3132 substr($self->{BUFFER},0,$end+4) = '';
3136 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3137 # (Folding Long Header Fields), 3.4.3 (Comments)
3138 # and 3.4.5 (Quoted-Strings).
3140 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3141 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3142 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3143 my ($field_name,$field_value) = ($1,$2); # avoid taintedness
3144 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3145 $return{$field_name}=$field_value;
3151 # This reads and returns the body as a single scalar value.
3152 'readBody' => <<'END_OF_FUNC',
3157 while (defined($data = $self->read)) {
3158 $returnval .= $data;
3164 # This will read $bytes or until the boundary is hit, whichever happens
3165 # first. After the boundary is hit, we return undef. The next read will
3166 # skip over the boundary and begin reading again;
3167 'read' => <<'END_OF_FUNC',
3169 my($self,$bytes) = @_;
3171 # default number of bytes to read
3172 $bytes = $bytes || $FILLUNIT;
3174 # Fill up our internal buffer in such a way that the boundary
3175 # is never split between reads.
3176 $self->fillBuffer($bytes);
3178 # Find the boundary in the buffer (it may not be there).
3179 my $start = index($self->{BUFFER},$self->{BOUNDARY});
3180 # protect against malformed multipart POST operations
3181 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3183 # If the boundary begins the data, then skip past it
3184 # and return undef. The +2 here is a fiendish plot to
3185 # remove the CR/LF pair at the end of the boundary.
3188 # clear us out completely if we've hit the last boundary.
3189 if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
3195 # just remove the boundary.
3196 substr($self->{BUFFER},0,length($self->{BOUNDARY})+2)='';
3201 if ($start > 0) { # read up to the boundary
3202 $bytesToReturn = $start > $bytes ? $bytes : $start;
3203 } else { # read the requested number of bytes
3204 # leave enough bytes in the buffer to allow us to read
3205 # the boundary. Thanks to Kevin Hendrick for finding
3207 $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
3210 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3211 substr($self->{BUFFER},0,$bytesToReturn)='';
3213 # If we hit the boundary, remove the CRLF from the end.
3214 return ($start > 0) ? substr($returnval,0,-2) : $returnval;
3219 # This fills up our internal buffer in such a way that the
3220 # boundary is never split between reads
3221 'fillBuffer' => <<'END_OF_FUNC',
3223 my($self,$bytes) = @_;
3224 return unless $self->{LENGTH};
3226 my($boundaryLength) = length($self->{BOUNDARY});
3227 my($bufferLength) = length($self->{BUFFER});
3228 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3229 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3231 # Try to read some data. We may hang here if the browser is screwed up.
3232 my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
3236 $self->{BUFFER} = '' unless defined $self->{BUFFER};
3238 # An apparent bug in the Apache server causes the read()
3239 # to return zero bytes repeatedly without blocking if the
3240 # remote user aborts during a file transfer. I don't know how
3241 # they manage this, but the workaround is to abort if we get
3242 # more than SPIN_LOOP_MAX consecutive zero reads.
3243 if ($bytesRead == 0) {
3244 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3245 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3247 $self->{ZERO_LOOP_COUNTER}=0;
3250 $self->{LENGTH} -= $bytesRead;
3255 # Return true when we've finished reading
3256 'eof' => <<'END_OF_FUNC'
3259 return 1 if (length($self->{BUFFER}) == 0)
3260 && ($self->{LENGTH} <= 0);
3268 ####################################################################################
3269 ################################## TEMPORARY FILES #################################
3270 ####################################################################################
3274 $MAC = $CGI::OS eq 'MACINTOSH';
3275 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3276 unless ($TMPDIRECTORY) {
3277 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3278 "C:${SL}temp","${SL}tmp","${SL}temp",
3279 "${vol}${SL}Temporary Items",
3281 unshift(@TEMP,$ENV{'TMPDIR'}) if exists $ENV{'TMPDIR'};
3284 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3285 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3286 # : can generate a 'getpwuid() not implemented' exception, even though
3287 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3288 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3289 unshift(@TEMP,(eval {(getpwuid($<))[7]}).'/tmp') if $CGI::OS eq 'UNIX';
3292 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3296 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3299 # cute feature, but overload implementation broke it
3300 # %OVERLOAD = ('""'=>'as_string');
3301 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3303 ###############################################################################
3304 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3305 ###############################################################################
3306 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3307 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3310 'new' => <<'END_OF_FUNC',
3312 my($package,$sequence) = @_;
3314 for (my $i = 0; $i < $MAXTRIES; $i++) {
3315 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3317 # untaint the darn thing
3318 return unless $filename =~ m!^([a-zA-Z0-9_ '":/\\]+)$!;
3320 return bless \$filename;
3324 'DESTROY' => <<'END_OF_FUNC',
3327 unlink $$self; # get rid of the file
3331 'as_string' => <<'END_OF_FUNC'
3343 # We get a whole bunch of warnings about "possibly uninitialized variables"
3344 # when running with the -w switch. Touch them all once to get rid of the
3345 # warnings. This is ugly and I hate it.
3350 $MultipartBuffer::SPIN_LOOP_MAX;
3351 $MultipartBuffer::CRLF;
3352 $MultipartBuffer::TIMEOUT;
3353 $MultipartBuffer::INITIAL_FILLUNIT;
3364 CGI - Simple Common Gateway Interface Class
3368 # CGI script that creates a fill-out form
3369 # and echoes back its values.
3371 use CGI qw/:standard/;
3373 start_html('A Simple Example'),
3374 h1('A Simple Example'),
3376 "What's your name? ",textfield('name'),p,
3377 "What's the combination?", p,
3378 checkbox_group(-name=>'words',
3379 -values=>['eenie','meenie','minie','moe'],
3380 -defaults=>['eenie','minie']), p,
3381 "What's your favorite color? ",
3382 popup_menu(-name=>'color',
3383 -values=>['red','green','blue','chartreuse']),p,
3389 print "Your name is",em(param('name')),p,
3390 "The keywords are: ",em(join(", ",param('words'))),p,
3391 "Your favorite color is ",em(param('color')),
3397 This perl library uses perl5 objects to make it easy to create Web
3398 fill-out forms and parse their contents. This package defines CGI
3399 objects, entities that contain the values of the current query string
3400 and other state variables. Using a CGI object's methods, you can
3401 examine keywords and parameters passed to your script, and create
3402 forms whose initial values are taken from the current query (thereby
3403 preserving state information). The module provides shortcut functions
3404 that produce boilerplate HTML, reducing typing and coding errors. It
3405 also provides functionality for some of the more advanced features of
3406 CGI scripting, including support for file uploads, cookies, cascading
3407 style sheets, server push, and frames.
3409 CGI.pm also provides a simple function-oriented programming style for
3410 those who don't need its object-oriented features.
3412 The current version of CGI.pm is available at
3414 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3415 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3419 =head2 PROGRAMMING STYLE
3421 There are two styles of programming with CGI.pm, an object-oriented
3422 style and a function-oriented style. In the object-oriented style you
3423 create one or more CGI objects and then use object methods to create
3424 the various elements of the page. Each CGI object starts out with the
3425 list of named parameters that were passed to your CGI script by the
3426 server. You can modify the objects, save them to a file or database
3427 and recreate them. Because each object corresponds to the "state" of
3428 the CGI script, and because each object's parameter list is
3429 independent of the others, this allows you to save the state of the
3430 script and restore it later.
3432 For example, using the object oriented style, here is how you create
3433 a simple "Hello World" HTML page:
3435 #!/usr/local/bin/perl -w
3436 use CGI; # load CGI routines
3437 $q = new CGI; # create new CGI object
3438 print $q->header, # create the HTTP header
3439 $q->start_html('hello world'), # start the HTML
3440 $q->h1('hello world'), # level 1 header
3441 $q->end_html; # end the HTML
3443 In the function-oriented style, there is one default CGI object that
3444 you rarely deal with directly. Instead you just call functions to
3445 retrieve CGI parameters, create HTML tags, manage cookies, and so
3446 on. This provides you with a cleaner programming interface, but
3447 limits you to using one CGI object at a time. The following example
3448 prints the same page, but uses the function-oriented interface.
3449 The main differences are that we now need to import a set of functions
3450 into our name space (usually the "standard" functions), and we don't
3451 need to create the CGI object.
3453 #!/usr/local/bin/perl
3454 use CGI qw/:standard/; # load standard CGI routines
3455 print header, # create the HTTP header
3456 start_html('hello world'), # start the HTML
3457 h1('hello world'), # level 1 header
3458 end_html; # end the HTML
3460 The examples in this document mainly use the object-oriented style.
3461 See HOW TO IMPORT FUNCTIONS for important information on
3462 function-oriented programming in CGI.pm
3464 =head2 CALLING CGI.PM ROUTINES
3466 Most CGI.pm routines accept several arguments, sometimes as many as 20
3467 optional ones! To simplify this interface, all routines use a named
3468 argument calling style that looks like this:
3470 print $q->header(-type=>'image/gif',-expires=>'+3d');
3472 Each argument name is preceded by a dash. Neither case nor order
3473 matters in the argument list. -type, -Type, and -TYPE are all
3474 acceptable. In fact, only the first argument needs to begin with a
3475 dash. If a dash is present in the first argument, CGI.pm assumes
3476 dashes for the subsequent ones.
3478 You don't have to use the hyphen at all if you don't want to. After
3479 creating a CGI object, call the B<use_named_parameters()> method with
3480 a nonzero value. This will tell CGI.pm that you intend to use named
3481 parameters exclusively:
3484 $query->use_named_parameters(1);
3485 $field = $query->radio_group('name'=>'OS',
3486 'values'=>['Unix','Windows','Macintosh'],
3489 Several routines are commonly called with just one argument. In the
3490 case of these routines you can provide the single argument without an
3491 argument name. header() happens to be one of these routines. In this
3492 case, the single argument is the document type.
3494 print $q->header('text/html');
3496 Other such routines are documented below.
3498 Sometimes named arguments expect a scalar, sometimes a reference to an
3499 array, and sometimes a reference to a hash. Often, you can pass any
3500 type of argument and the routine will do whatever is most appropriate.
3501 For example, the param() routine is used to set a CGI parameter to a
3502 single or a multi-valued value. The two cases are shown below:
3504 $q->param(-name=>'veggie',-value=>'tomato');
3505 $q->param(-name=>'veggie',-value=>'[tomato','tomahto','potato','potahto']);
3507 A large number of routines in CGI.pm actually aren't specifically
3508 defined in the module, but are generated automatically as needed.
3509 These are the "HTML shortcuts," routines that generate HTML tags for
3510 use in dynamically-generated pages. HTML tags have both attributes
3511 (the attribute="value" pairs within the tag itself) and contents (the
3512 part between the opening and closing pairs.) To distinguish between
3513 attributes and contents, CGI.pm uses the convention of passing HTML
3514 attributes as a hash reference as the first argument, and the
3515 contents, if any, as any subsequent arguments. It works out like
3521 h1('some','contents'); <H1>some contents</H1>
3522 h1({-align=>left}); <H1 ALIGN="LEFT">
3523 h1({-align=>left},'contents'); <H1 ALIGN="LEFT">contents</H1>
3525 HTML tags are described in more detail later.
3527 Many newcomers to CGI.pm are puzzled by the difference between the
3528 calling conventions for the HTML shortcuts, which require curly braces
3529 around the HTML tag attributes, and the calling conventions for other
3530 routines, which manage to generate attributes without the curly
3531 brackets. Don't be confused. As a convenience the curly braces are
3532 optional in all but the HTML shortcuts. If you like, you can use
3533 curly braces when calling any routine that takes named arguments. For
3536 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3538 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3539 names conflict with built-in Perl functions. The most frequent of
3540 these is the -values argument, used to create multi-valued menus,
3541 radio button clusters and the like. To get around this warning, you
3542 have several choices:
3546 =item 1. Use another name for the argument, if one is available. For
3547 example, -value is an alias for -values.
3549 =item 2. Change the capitalization, e.g. -Values
3551 =item 3. Put quotes around the argument name, e.g. '-values'
3555 Many routines will do something useful with a named argument that it
3556 doesn't recognize. For example, you can produce non-standard HTTP
3557 header fields by providing them as named arguments:
3559 print $q->header(-type => 'text/html',
3560 -cost => 'Three smackers',
3561 -annoyance_level => 'high',
3562 -complaints_to => 'bit bucket');
3564 This will produce the following nonstandard HTTP header:
3567 Cost: Three smackers
3568 Annoyance-level: high
3569 Complaints-to: bit bucket
3570 Content-type: text/html
3572 Notice the way that underscores are translated automatically into
3573 hyphens. HTML-generating routines perform a different type of
3576 This feature allows you to keep up with the rapidly changing HTTP and
3579 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
3583 This will parse the input (from both POST and GET methods) and store
3584 it into a perl5 object called $query.
3586 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
3588 $query = new CGI(INPUTFILE);
3590 If you provide a file handle to the new() method, it will read
3591 parameters from the file (or STDIN, or whatever). The file can be in
3592 any of the forms describing below under debugging (i.e. a series of
3593 newline delimited TAG=VALUE pairs will work). Conveniently, this type
3594 of file is created by the save() method (see below). Multiple records
3595 can be saved and restored.
3597 Perl purists will be pleased to know that this syntax accepts
3598 references to file handles, or even references to filehandle globs,
3599 which is the "official" way to pass a filehandle:
3601 $query = new CGI(\*STDIN);
3603 You can also initialize the CGI object with a FileHandle or IO::File
3606 If you are using the function-oriented interface and want to
3607 initialize CGI state from a file handle, the way to do this is with
3608 B<restore_parameters()>. This will (re)initialize the
3609 default CGI object from the indicated file handle.
3611 open (IN,"test.in") || die;
3612 restore_parameters(IN);
3615 You can also initialize the query object from an associative array
3618 $query = new CGI( {'dinosaur'=>'barney',
3619 'song'=>'I love you',
3620 'friends'=>[qw/Jessica George Nancy/]}
3623 or from a properly formatted, URL-escaped query string:
3625 $query = new CGI('dinosaur=barney&color=purple');
3627 or from a previously existing CGI object (currently this clones the
3628 parameter list, but none of the other object-specific fields, such as
3631 $old_query = new CGI;
3632 $new_query = new CGI($old_query);
3634 To create an empty query, initialize it from an empty string or hash:
3636 $empty_query = new CGI("");
3640 $empty_query = new CGI({});
3642 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
3644 @keywords = $query->keywords
3646 If the script was invoked as the result of an <ISINDEX> search, the
3647 parsed keywords can be obtained as an array using the keywords() method.
3649 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
3651 @names = $query->param
3653 If the script was invoked with a parameter list
3654 (e.g. "name1=value1&name2=value2&name3=value3"), the param()
3655 method will return the parameter names as a list. If the
3656 script was invoked as an <ISINDEX> script, there will be a
3657 single parameter named 'keywords'.
3659 NOTE: As of version 1.5, the array of parameter names returned will
3660 be in the same order as they were submitted by the browser.
3661 Usually this order is the same as the order in which the
3662 parameters are defined in the form (however, this isn't part
3663 of the spec, and so isn't guaranteed).
3665 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
3667 @values = $query->param('foo');
3671 $value = $query->param('foo');
3673 Pass the param() method a single argument to fetch the value of the
3674 named parameter. If the parameter is multivalued (e.g. from multiple
3675 selections in a scrolling list), you can ask to receive an array. Otherwise
3676 the method will return a single value.
3678 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
3680 $query->param('foo','an','array','of','values');
3682 This sets the value for the named parameter 'foo' to an array of
3683 values. This is one way to change the value of a field AFTER
3684 the script has been invoked once before. (Another way is with
3685 the -override parameter accepted by all methods that generate
3688 param() also recognizes a named parameter style of calling described
3689 in more detail later:
3691 $query->param(-name=>'foo',-values=>['an','array','of','values']);
3695 $query->param(-name=>'foo',-value=>'the value');
3697 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
3699 $query->append(-name=>'foo',-values=>['yet','more','values']);
3701 This adds a value or list of values to the named parameter. The
3702 values are appended to the end of the parameter if it already exists.
3703 Otherwise the parameter is created. Note that this method only
3704 recognizes the named argument calling syntax.
3706 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
3708 $query->import_names('R');
3710 This creates a series of variables in the 'R' namespace. For example,
3711 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
3712 If no namespace is given, this method will assume 'Q'.
3713 WARNING: don't import anything into 'main'; this is a major security
3716 In older versions, this method was called B<import()>. As of version 2.20,
3717 this name has been removed completely to avoid conflict with the built-in
3718 Perl module B<import> operator.
3720 =head2 DELETING A PARAMETER COMPLETELY:
3722 $query->delete('foo');
3724 This completely clears a parameter. It sometimes useful for
3725 resetting parameters that you don't want passed down between
3728 If you are using the function call interface, use "Delete()" instead
3729 to avoid conflicts with Perl's built-in delete operator.
3731 =head2 DELETING ALL PARAMETERS:
3733 $query->delete_all();
3735 This clears the CGI object completely. It might be useful to ensure
3736 that all the defaults are taken when you create a fill-out form.
3738 Use Delete_all() instead if you are using the function call interface.
3740 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
3742 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
3743 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
3745 If you need access to the parameter list in a way that isn't covered
3746 by the methods above, you can obtain a direct reference to it by
3747 calling the B<param_fetch()> method with the name of the . This
3748 will return an array reference to the named parameters, which you then
3749 can manipulate in any way you like.
3751 You can also use a named argument style using the B<-name> argument.
3753 =head2 FETCHING THE PARAMETER LIST AS A HASH:
3756 print $params->{'address'};
3757 @foo = split("\0",$params->{'foo'});
3763 Many people want to fetch the entire parameter list as a hash in which
3764 the keys are the names of the CGI parameters, and the values are the
3765 parameters' values. The Vars() method does this. Called in a scalar
3766 context, it returns the parameter list as a tied hash reference.
3767 Changing a key changes the value of the parameter in the underlying
3768 CGI parameter list. Called in an array context, it returns the
3769 parameter list as an ordinary hash. This allows you to read the
3770 contents of the parameter list, but not to change it.
3772 When using this, the thing you must watch out for are multivalued CGI
3773 parameters. Because a hash cannot distinguish between scalar and
3774 array context, multivalued parameters will be returned as a packed
3775 string, separated by the "\0" (null) character. You must split this
3776 packed string in order to get at the individual values. This is the
3777 convention introduced long ago by Steve Brenner in his cgi-lib.pl
3778 module for Perl version 4.
3780 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
3781 function calls (also see the section on CGI-LIB compatibility).
3783 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
3785 $query->save(FILEHANDLE)
3787 This will write the current state of the form to the provided
3788 filehandle. You can read it back in by providing a filehandle
3789 to the new() method. Note that the filehandle can be a file, a pipe,
3792 The format of the saved file is:
3800 Both name and value are URL escaped. Multi-valued CGI parameters are
3801 represented as repeated names. A session record is delimited by a
3802 single = symbol. You can write out multiple records and read them
3803 back in with several calls to B<new>. You can do this across several
3804 sessions by opening the file in append mode, allowing you to create
3805 primitive guest books, or to keep a history of users' queries. Here's
3806 a short example of creating multiple session records:
3810 open (OUT,">>test.out") || die;
3812 foreach (0..$records) {
3814 $q->param(-name=>'counter',-value=>$_);
3819 # reopen for reading
3820 open (IN,"test.out") || die;
3822 my $q = new CGI(IN);
3823 print $q->param('counter'),"\n";
3826 The file format used for save/restore is identical to that used by the
3827 Whitehead Genome Center's data exchange format "Boulderio", and can be
3828 manipulated and even databased using Boulderio utilities. See
3830 http://stein.cshl.org/boulder/
3832 for further details.
3834 If you wish to use this method from the function-oriented (non-OO)
3835 interface, the exported name for this method is B<save_parameters()>.
3837 =head2 RETRIEVING CGI ERRORS
3839 Errors can occur while processing user input, particularly when
3840 processing uploaded files. When these errors occur, CGI will stop
3841 processing and return an empty parameter list. You can test for
3842 the existence and nature of errors using the I<cgi_error()> function.
3843 The error messages are formatted as HTTP status codes. You can either
3844 incorporate the error text into an HTML page, or use it as the value
3847 my $error = $q->cgi_error;
3849 print $q->header(-status=>$error),
3850 $q->start_html('Problems'),
3851 $q->h2('Request not processed'),
3856 When using the function-oriented interface (see the next section),
3857 errors may only occur the first time you call I<param()>. Be ready
3860 =head2 USING THE FUNCTION-ORIENTED INTERFACE
3862 To use the function-oriented interface, you must specify which CGI.pm
3863 routines or sets of routines to import into your script's namespace.
3864 There is a small overhead associated with this importation, but it
3867 use CGI <list of methods>;
3869 The listed methods will be imported into the current package; you can
3870 call them directly without creating a CGI object first. This example
3871 shows how to import the B<param()> and B<header()>
3872 methods, and then use them directly:
3874 use CGI 'param','header';
3875 print header('text/plain');
3876 $zipcode = param('zipcode');
3878 More frequently, you'll import common sets of functions by referring
3879 to the groups by name. All function sets are preceded with a ":"
3880 character as in ":html3" (for tags defined in the HTML 3 standard).
3882 Here is a list of the function sets you can import:
3888 Import all CGI-handling methods, such as B<param()>, B<path_info()>
3893 Import all fill-out form generating methods, such as B<textfield()>.
3897 Import all methods that generate HTML 2.0 standard elements.
3901 Import all methods that generate HTML 3.0 proposed elements (such as
3902 <table>, <super> and <sub>).
3906 Import all methods that generate Netscape-specific HTML extensions.
3910 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
3915 Import "standard" features, 'html2', 'html3', 'form' and 'cgi'.
3919 Import all the available methods. For the full list, see the CGI.pm
3920 code, where the variable %EXPORT_TAGS is defined.
3924 If you import a function name that is not part of CGI.pm, the module
3925 will treat it as a new HTML tag and generate the appropriate
3926 subroutine. You can then use it like any other HTML tag. This is to
3927 provide for the rapidly-evolving HTML "standard." For example, say
3928 Microsoft comes out with a new tag called <GRADIENT> (which causes the
3929 user's desktop to be flooded with a rotating gradient fill until his
3930 machine reboots). You don't need to wait for a new version of CGI.pm
3931 to start using it immediately:
3933 use CGI qw/:standard :html3 gradient/;
3934 print gradient({-start=>'red',-end=>'blue'});
3936 Note that in the interests of execution speed CGI.pm does B<not> use
3937 the standard L<Exporter> syntax for specifying load symbols. This may
3938 change in the future.
3940 If you import any of the state-maintaining CGI or form-generating
3941 methods, a default CGI object will be created and initialized
3942 automatically the first time you use any of the methods that require
3943 one to be present. This includes B<param()>, B<textfield()>,
3944 B<submit()> and the like. (If you need direct access to the CGI
3945 object, you can find it in the global variable B<$CGI::Q>). By
3946 importing CGI.pm methods, you can create visually elegant scripts:
3948 use CGI qw/:standard/;
3951 start_html('Simple Script'),
3952 h1('Simple Script'),
3954 "What's your name? ",textfield('name'),p,
3955 "What's the combination?",
3956 checkbox_group(-name=>'words',
3957 -values=>['eenie','meenie','minie','moe'],
3958 -defaults=>['eenie','moe']),p,
3959 "What's your favorite color?",
3960 popup_menu(-name=>'color',
3961 -values=>['red','green','blue','chartreuse']),p,
3968 "Your name is ",em(param('name')),p,
3969 "The keywords are: ",em(join(", ",param('words'))),p,
3970 "Your favorite color is ",em(param('color')),".\n";
3976 In addition to the function sets, there are a number of pragmas that
3977 you can import. Pragmas, which are always preceded by a hyphen,
3978 change the way that CGI.pm functions in various ways. Pragmas,
3979 function sets, and individual functions can all be imported in the
3980 same use() line. For example, the following use statement imports the
3981 standard set of functions and disables debugging mode (pragma
3984 use CGI qw/:standard -no_debug/;
3986 The current list of pragmas is as follows:
3992 When you I<use CGI -any>, then any method that the query object
3993 doesn't recognize will be interpreted as a new HTML tag. This allows
3994 you to support the next I<ad hoc> Netscape or Microsoft HTML
3995 extension. This lets you go wild with new and unsupported tags:
3999 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4001 Since using <cite>any</cite> causes any mistyped method name
4002 to be interpreted as an HTML tag, use it with care or not at
4007 This causes the indicated autoloaded methods to be compiled up front,
4008 rather than deferred to later. This is useful for scripts that run
4009 for an extended period of time under FastCGI or mod_perl, and for
4010 those destined to be crunched by Malcom Beattie's Perl compiler. Use
4011 it in conjunction with the methods or method families you plan to use.
4013 use CGI qw(-compile :standard :html3);
4017 use CGI qw(-compile :all);
4019 Note that using the -compile pragma in this way will always have
4020 the effect of importing the compiled functions into the current
4021 namespace. If you want to compile without importing use the
4022 compile() method instead (see below).
4026 This makes CGI.pm produce a header appropriate for an NPH (no
4027 parsed header) script. You may need to do other things as well
4028 to tell the server that the script is NPH. See the discussion
4029 of NPH scripts below.
4031 =item -newstyle_urls
4033 Separate the name=value pairs in CGI parameter query strings with
4034 semicolons rather than ampersands. For example:
4036 ?name=fred;age=24;favorite_color=3
4038 Semicolon-delimited query strings are always accepted, but will not be
4039 emitted by self_url() and query_string() unless the -newstyle_urls
4040 pragma is specified.
4044 This overrides the autoloader so that any function in your program
4045 that is not recognized is referred to CGI.pm for possible evaluation.
4046 This allows you to use all the CGI.pm functions without adding them to
4047 your symbol table, which is of concern for mod_perl users who are
4048 worried about memory consumption. I<Warning:> when
4049 I<-autoload> is in effect, you cannot use "poetry mode"
4050 (functions without the parenthesis). Use I<hr()> rather
4051 than I<hr>, or add something like I<use subs qw/hr p header/>
4052 to the top of your script.
4056 This turns off the command-line processing features. If you want to
4057 run a CGI.pm script from the command line to produce HTML, and you
4058 don't want it pausing to request CGI parameters from standard input or
4059 the command line, then use this pragma:
4061 use CGI qw(-no_debug :standard);
4063 If you'd like to process the command-line parameters but not standard
4064 input, this should work:
4066 use CGI qw(-no_debug :standard);
4067 restore_parameters(join('&',@ARGV));
4069 See the section on debugging for more details.
4071 =item -private_tempfiles
4073 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4074 file to a temporary directory, then deletes the file when done.
4075 However, this opens the risk of eavesdropping as described in the file
4076 upload section. Another CGI script author could peek at this data
4077 during the upload, even if it is confidential information. On Unix
4078 systems, the -private_tempfiles pragma will cause the temporary file
4079 to be unlinked as soon as it is opened and before any data is written
4080 into it, reducing, but not eliminating the risk of eavesdropping
4081 (there is still a potential race condition). To make life harder for
4082 the attacker, the program chooses tempfile names by calculating a 32
4083 bit checksum of the incoming HTTP headers.
4085 To ensure that the temporary file cannot be read by other CGI scripts,
4086 use suEXEC or a CGI wrapper program to run your script. The temporary
4087 file is created with mode 0600 (neither world nor group readable).
4089 The temporary directory is selected using the following algorithm:
4091 1. if the current user (e.g. "nobody") has a directory named
4092 "tmp" in its home directory, use that (Unix systems only).
4094 2. if the environment variable TMPDIR exists, use the location
4097 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4098 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4100 Each of these locations is checked that it is a directory and is
4101 writable. If not, the algorithm tries the next choice.
4105 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4107 Many of the methods generate HTML tags. As described below, tag
4108 functions automatically generate both the opening and closing tags.
4111 print h1('Level 1 Header');
4115 <H1>Level 1 Header</H1>
4117 There will be some times when you want to produce the start and end
4118 tags yourself. In this case, you can use the form start_I<tag_name>
4119 and end_I<tag_name>, as in:
4121 print start_h1,'Level 1 Header',end_h1;
4123 With a few exceptions (described below), start_I<tag_name> and
4124 end_I<tag_name> functions are not generated automatically when you
4125 I<use CGI>. However, you can specify the tags you want to generate
4126 I<start/end> functions for by putting an asterisk in front of their
4127 name, or, alternatively, requesting either "start_I<tag_name>" or
4128 "end_I<tag_name>" in the import list.
4132 use CGI qw/:standard *table start_ul/;
4134 In this example, the following functions are generated in addition to
4139 =item 1. start_table() (generates a <TABLE> tag)
4141 =item 2. end_table() (generates a </TABLE> tag)
4143 =item 3. start_ul() (generates a <UL> tag)
4145 =item 4. end_ul() (generates a </UL> tag)
4149 =head1 GENERATING DYNAMIC DOCUMENTS
4151 Most of CGI.pm's functions deal with creating documents on the fly.
4152 Generally you will produce the HTTP header first, followed by the
4153 document itself. CGI.pm provides functions for generating HTTP
4154 headers of various types as well as for generating HTML. For creating
4155 GIF images, see the GD.pm module.
4157 Each of these functions produces a fragment of HTML or HTTP which you
4158 can print out directly so that it displays in the browser window,
4159 append to a string, or save to a file for later use.
4161 =head2 CREATING A STANDARD HTTP HEADER:
4163 Normally the first thing you will do in any CGI script is print out an
4164 HTTP header. This tells the browser what type of document to expect,
4165 and gives other optional information, such as the language, expiration
4166 date, and whether to cache the document. The header can also be
4167 manipulated for special purposes, such as server push and pay per view
4170 print $query->header;
4174 print $query->header('image/gif');
4178 print $query->header('text/html','204 No response');
4182 print $query->header(-type=>'image/gif',
4184 -status=>'402 Payment required',
4189 header() returns the Content-type: header. You can provide your own
4190 MIME type if you choose, otherwise it defaults to text/html. An
4191 optional second parameter specifies the status code and a human-readable
4192 message. For example, you can specify 204, "No response" to create a
4193 script that tells the browser to do nothing at all.
4195 The last example shows the named argument style for passing arguments
4196 to the CGI methods using named parameters. Recognized parameters are
4197 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
4198 parameters will be stripped of their initial hyphens and turned into
4199 header fields, allowing you to specify any HTTP header you desire.
4200 Internal underscores will be turned into hyphens:
4202 print $query->header(-Content_length=>3002);
4204 Most browsers will not cache the output from CGI scripts. Every time
4205 the browser reloads the page, the script is invoked anew. You can
4206 change this behavior with the B<-expires> parameter. When you specify
4207 an absolute or relative expiration interval with this parameter, some
4208 browsers and proxy servers will cache the script's output until the
4209 indicated expiration date. The following forms are all valid for the
4212 +30s 30 seconds from now
4213 +10m ten minutes from now
4214 +1h one hour from now
4215 -1d yesterday (i.e. "ASAP!")
4218 +10y in ten years time
4219 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
4221 The B<-cookie> parameter generates a header that tells the browser to provide
4222 a "magic cookie" during all subsequent transactions with your script.
4223 Netscape cookies have a special format that includes interesting attributes
4224 such as expiration time. Use the cookie() method to create and retrieve
4227 The B<-nph> parameter, if set to a true value, will issue the correct
4228 headers to work with a NPH (no-parse-header) script. This is important
4229 to use with certain servers, such as Microsoft Internet Explorer, which
4230 expect all their scripts to be NPH.
4232 =head2 GENERATING A REDIRECTION HEADER
4234 print $query->redirect('http://somewhere.else/in/movie/land');
4236 Sometimes you don't want to produce a document yourself, but simply
4237 redirect the browser elsewhere, perhaps choosing a URL based on the
4238 time of day or the identity of the user.
4240 The redirect() function redirects the browser to a different URL. If
4241 you use redirection like this, you should B<not> print out a header as
4242 well. As of version 2.0, we produce both the unofficial Location:
4243 header and the official URI: header. This should satisfy most servers
4246 One hint I can offer is that relative links may not work correctly
4247 when you generate a redirection to another document on your site.
4248 This is due to a well-intentioned optimization that some servers use.
4249 The solution to this is to use the full URL (including the http: part)
4250 of the document you are redirecting to.
4252 You can also use named arguments:
4254 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4257 The B<-nph> parameter, if set to a true value, will issue the correct
4258 headers to work with a NPH (no-parse-header) script. This is important
4259 to use with certain servers, such as Microsoft Internet Explorer, which
4260 expect all their scripts to be NPH.
4262 =head2 CREATING THE HTML DOCUMENT HEADER
4264 print $query->start_html(-title=>'Secrets of the Pyramids',
4265 -author=>'fred@capricorn.org',
4268 -meta=>{'keywords'=>'pharaoh secret mummy',
4269 'copyright'=>'copyright 1996 King Tut'},
4270 -style=>{'src'=>'/styles/style1.css'},
4273 After creating the HTTP header, most CGI scripts will start writing
4274 out an HTML document. The start_html() routine creates the top of the
4275 page, along with a lot of optional information that controls the
4276 page's appearance and behavior.
4278 This method returns a canned HTML header and the opening <BODY> tag.
4279 All parameters are optional. In the named parameter form, recognized
4280 parameters are -title, -author, -base, -xbase and -target (see below
4281 for the explanation). Any additional parameters you provide, such as
4282 the Netscape unofficial BGCOLOR attribute, are added to the <BODY>
4283 tag. Additional parameters must be proceeded by a hyphen.
4285 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
4286 different from the current location, as in
4288 -xbase=>"http://home.mcom.com/"
4290 All relative links will be interpreted relative to this tag.
4292 The argument B<-target> allows you to provide a default target frame
4293 for all the links and fill-out forms on the page. See the Netscape
4294 documentation on frames for details of how to manipulate this.
4296 -target=>"answer_window"
4298 All relative links will be interpreted relative to this tag.
4299 You add arbitrary meta information to the header with the B<-meta>
4300 argument. This argument expects a reference to an associative array
4301 containing name/value pairs of meta information. These will be turned
4302 into a series of header <META> tags that look something like this:
4304 <META NAME="keywords" CONTENT="pharaoh secret mummy">
4305 <META NAME="description" CONTENT="copyright 1996 King Tut">
4307 There is no support for the HTTP-EQUIV type of <META> tag. This is
4308 because you can modify the HTTP header directly with the B<header()>
4309 method. For example, if you want to send the Refresh: header, do it
4310 in the header() method:
4312 print $q->header(-Refresh=>'10; URL=http://www.capricorn.com');
4314 The B<-style> tag is used to incorporate cascading stylesheets into
4315 your code. See the section on CASCADING STYLESHEETS for more information.
4317 You can place other arbitrary HTML elements to the <HEAD> section with the
4318 B<-head> tag. For example, to place the rarely-used <LINK> element in the
4319 head section, use this:
4321 print start_html(-head=>Link({-rel=>'next',
4322 -href=>'http://www.capricorn.com/s2.html'}));
4324 To incorporate multiple HTML elements into the <HEAD> section, just pass an
4327 print start_html(-head=>[
4329 -href=>'http://www.capricorn.com/s2.html'}),
4330 Link({-rel=>'previous',
4331 -href=>'http://www.capricorn.com/s1.html'})
4335 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4336 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4337 to add Netscape JavaScript calls to your pages. B<-script> should
4338 point to a block of text containing JavaScript function definitions.
4339 This block will be placed within a <SCRIPT> block inside the HTML (not
4340 HTTP) header. The block is placed in the header in order to give your
4341 page a fighting chance of having all its JavaScript functions in place
4342 even if the user presses the stop button before the page has loaded
4343 completely. CGI.pm attempts to format the script in such a way that
4344 JavaScript-naive browsers will not choke on the code: unfortunately
4345 there are some browsers, such as Chimera for Unix, that get confused
4348 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4349 code to execute when the page is respectively opened and closed by the
4350 browser. Usually these parameters are calls to functions defined in the
4354 print $query->header;
4356 // Ask a silly question
4357 function riddle_me_this() {
4358 var r = prompt("What walks on four legs in the morning, " +
4359 "two legs in the afternoon, " +
4360 "and three legs in the evening?");
4363 // Get a silly answer
4364 function response(answer) {
4365 if (answer == "man")
4366 alert("Right you are!");
4368 alert("Wrong! Guess again.");
4371 print $query->start_html(-title=>'The Riddle of the Sphinx',
4374 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4375 browsers that do not have JavaScript (or browsers where JavaScript is turned
4378 Netscape 3.0 recognizes several attributes of the <SCRIPT> tag,
4379 including LANGUAGE and SRC. The latter is particularly interesting,
4380 as it allows you to keep the JavaScript code in a file or CGI script
4381 rather than cluttering up each page with the source. To use these
4382 attributes pass a HASH reference in the B<-script> parameter containing
4383 one or more of -language, -src, or -code:
4385 print $q->start_html(-title=>'The Riddle of the Sphinx',
4386 -script=>{-language=>'JAVASCRIPT',
4387 -src=>'/javascript/sphinx.js'}
4390 print $q->(-title=>'The Riddle of the Sphinx',
4391 -script=>{-language=>'PERLSCRIPT',
4392 -code=>'print "hello world!\n;"'}
4396 A final feature allows you to incorporate multiple <SCRIPT> sections into the
4397 header. Just pass the list of script sections as an array reference.
4398 this allows you to specify different source files for different dialects
4399 of JavaScript. Example:
4401 print $q->start_html(-title=>'The Riddle of the Sphinx',
4403 { -language => 'JavaScript1.0',
4404 -src => '/javascript/utilities10.js'
4406 { -language => 'JavaScript1.1',
4407 -src => '/javascript/utilities11.js'
4409 { -language => 'JavaScript1.2',
4410 -src => '/javascript/utilities12.js'
4412 { -language => 'JavaScript28.2',
4413 -src => '/javascript/utilities219.js'
4419 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4423 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4425 for more information about JavaScript.
4427 The old-style positional parameters are as follows:
4431 =item B<Parameters:>
4439 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
4443 A 'true' flag if you want to include a <BASE> tag in the header. This
4444 helps resolve relative addresses to absolute ones when the document is moved,
4445 but makes the document hierarchy non-portable. Use with care!
4449 Any other parameters you want to include in the <BODY> tag. This is a good
4450 place to put Netscape extensions, such as colors and wallpaper patterns.
4454 =head2 ENDING THE HTML DOCUMENT:
4456 print $query->end_html
4458 This ends an HTML document by printing the </BODY></HTML> tags.
4460 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4462 $myself = $query->self_url;
4463 print "<A HREF=$myself>I'm talking to myself.</A>";
4465 self_url() will return a URL, that, when selected, will reinvoke
4466 this script with all its state information intact. This is most
4467 useful when you want to jump around within the document using
4468 internal anchors but you don't want to disrupt the current contents
4469 of the form(s). Something like this will do the trick.
4471 $myself = $query->self_url;
4472 print "<A HREF=$myself#table1>See table 1</A>";
4473 print "<A HREF=$myself#table2>See table 2</A>";
4474 print "<A HREF=$myself#yourself>See for yourself</A>";
4476 If you want more control over what's returned, using the B<url()>
4479 You can also retrieve the unprocessed query string with query_string():
4481 $the_string = $query->query_string;
4483 =head2 OBTAINING THE SCRIPT'S URL
4485 $full_url = $query->url();
4486 $full_url = $query->url(-full=>1); #alternative syntax
4487 $relative_url = $query->url(-relative=>1);
4488 $absolute_url = $query->url(-absolute=>1);
4489 $url_with_path = $query->url(-path_info=>1);
4490 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4492 B<url()> returns the script's URL in a variety of formats. Called
4493 without any arguments, it returns the full form of the URL, including
4494 host name and port number
4496 http://your.host.com/path/to/script.cgi
4498 You can modify this format with the following named arguments:
4504 If true, produce an absolute URL, e.g.
4510 Produce a relative URL. This is useful if you want to reinvoke your
4511 script with different parameters. For example:
4517 Produce the full URL, exactly as if called without any arguments.
4518 This overrides the -relative and -absolute arguments.
4520 =item B<-path> (B<-path_info>)
4522 Append the additional path information to the URL. This can be
4523 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
4524 is provided as a synonym.
4526 =item B<-query> (B<-query_string>)
4528 Append the query string to the URL. This can be combined with
4529 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
4534 =head2 MIXING POST AND URL PARAMETERS
4536 $color = $query->url_param('color');
4538 It is possible for a script to receive CGI parameters in the URL as
4539 well as in the fill-out form by creating a form that POSTs to a URL
4540 containing a query string (a "?" mark followed by arguments). The
4541 B<param()> method will always return the contents of the POSTed
4542 fill-out form, ignoring the URL's query string. To retrieve URL
4543 parameters, call the B<url_param()> method. Use it in the same way as
4544 B<param()>. The main difference is that it allows you to read the
4545 parameters, but not set them.
4548 Under no circumstances will the contents of the URL query string
4549 interfere with similarly-named CGI parameters in POSTed forms. If you
4550 try to mix a URL query string with a form submitted with the GET
4551 method, the results will not be what you expect.
4553 =head1 CREATING STANDARD HTML ELEMENTS:
4555 CGI.pm defines general HTML shortcut methods for most, if not all of
4556 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
4557 HTML element and return a fragment of HTML text that you can then
4558 print or manipulate as you like. Each shortcut returns a fragment of
4559 HTML code that you can append to a string, save to a file, or, most
4560 commonly, print out so that it displays in the browser window.
4562 This example shows how to use the HTML methods:
4565 print $q->blockquote(
4566 "Many years ago on the island of",
4567 $q->a({href=>"http://crete.org/"},"Crete"),
4568 "there lived a Minotaur named",
4569 $q->strong("Fred."),
4573 This results in the following HTML code (extra newlines have been
4574 added for readability):
4577 Many years ago on the island of
4578 <a HREF="http://crete.org/">Crete</a> there lived
4579 a minotaur named <strong>Fred.</strong>
4583 If you find the syntax for calling the HTML shortcuts awkward, you can
4584 import them into your namespace and dispense with the object syntax
4585 completely (see the next section for more details):
4587 use CGI ':standard';
4589 "Many years ago on the island of",
4590 a({href=>"http://crete.org/"},"Crete"),
4591 "there lived a minotaur named",
4596 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4598 The HTML methods will accept zero, one or multiple arguments. If you
4599 provide no arguments, you get a single tag:
4603 If you provide one or more string arguments, they are concatenated
4604 together with spaces and placed between opening and closing tags:
4606 print h1("Chapter","1"); # <H1>Chapter 1</H1>"
4608 If the first argument is an associative array reference, then the keys
4609 and values of the associative array become the HTML tag's attributes:
4611 print a({-href=>'fred.html',-target=>'_new'},
4612 "Open a new frame");
4614 <A HREF="fred.html",TARGET="_new">Open a new frame</A>
4616 You may dispense with the dashes in front of the attribute names if
4619 print img {src=>'fred.gif',align=>'LEFT'};
4621 <IMG ALIGN="LEFT" SRC="fred.gif">
4623 Sometimes an HTML tag attribute has no argument. For example, ordered
4624 lists can be marked as COMPACT. The syntax for this is an argument that
4625 that points to an undef string:
4627 print ol({compact=>undef},li('one'),li('two'),li('three'));
4629 Prior to CGI.pm version 2.41, providing an empty ('') string as an
4630 attribute argument was the same as providing undef. However, this has
4631 changed in order to accommodate those who want to create tags of the form
4632 <IMG ALT="">. The difference is shown in these two pieces of code:
4635 img({alt=>undef}) <IMG ALT>
4636 img({alt=>''}) <IMT ALT="">
4638 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
4640 One of the cool features of the HTML shortcuts is that they are
4641 distributive. If you give them an argument consisting of a
4642 B<reference> to a list, the tag will be distributed across each
4643 element of the list. For example, here's one way to make an ordered
4647 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy']);
4650 This example will result in HTML output that looks like this:
4653 <LI TYPE="disc">Sneezy</LI>
4654 <LI TYPE="disc">Doc</LI>
4655 <LI TYPE="disc">Sleepy</LI>
4656 <LI TYPE="disc">Happy</LI>
4659 This is extremely useful for creating tables. For example:
4661 print table({-border=>undef},
4662 caption('When Should You Eat Your Vegetables?'),
4663 Tr({-align=>CENTER,-valign=>TOP},
4665 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
4666 td(['Tomatoes' , 'no', 'yes', 'yes']),
4667 td(['Broccoli' , 'no', 'no', 'yes']),
4668 td(['Onions' , 'yes','yes', 'yes'])
4673 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
4675 Consider this bit of code:
4677 print blockquote(em('Hi'),'mom!'));
4679 It will ordinarily return the string that you probably expect, namely:
4681 <BLOCKQUOTE><EM>Hi</EM> mom!</BLOCKQUOTE>
4683 Note the space between the element "Hi" and the element "mom!".
4684 CGI.pm puts the extra space there using array interpolation, which is
4685 controlled by the magic $" variable. Sometimes this extra space is
4686 not what you want, for example, when you are trying to align a series
4687 of images. In this case, you can simply change the value of $" to an
4692 print blockquote(em('Hi'),'mom!'));
4695 I suggest you put the code in a block as shown here. Otherwise the
4696 change to $" will affect all subsequent code until you explicitly
4699 =head2 NON-STANDARD HTML SHORTCUTS
4701 A few HTML tags don't follow the standard pattern for various
4704 B<comment()> generates an HTML comment (<!-- comment -->). Call it
4707 print comment('here is my comment');
4709 Because of conflicts with built-in Perl functions, the following functions
4710 begin with initial caps:
4719 In addition, start_html(), end_html(), start_form(), end_form(),
4720 start_multipart_form() and all the fill-out form tags are special.
4721 See their respective sections.
4723 =head2 PRETTY-PRINTING HTML
4725 By default, all the HTML produced by these functions comes out as one
4726 long line without carriage returns or indentation. This is yuck, but
4727 it does reduce the size of the documents by 10-20%. To get
4728 pretty-printed output, please use L<CGI::Pretty>, a subclass
4729 contributed by Brian Paulsen.
4731 =head1 CREATING FILL-OUT FORMS:
4733 I<General note> The various form-creating methods all return strings
4734 to the caller, containing the tag or tags that will create the requested
4735 form element. You are responsible for actually printing out these strings.
4736 It's set up this way so that you can place formatting tags
4737 around the form elements.
4739 I<Another note> The default values that you specify for the forms are only
4740 used the B<first> time the script is invoked (when there is no query
4741 string). On subsequent invocations of the script (when there is a query
4742 string), the former values are used even if they are blank.
4744 If you want to change the value of a field from its previous value, you have two
4747 (1) call the param() method to set it.
4749 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
4750 This forces the default value to be used, regardless of the previous value:
4752 print $query->textfield(-name=>'field_name',
4753 -default=>'starting value',
4758 I<Yet another note> By default, the text and labels of form elements are
4759 escaped according to HTML rules. This means that you can safely use
4760 "<CLICK ME>" as the label for a button. However, it also interferes with
4761 your ability to incorporate special HTML character sequences, such as Á,
4762 into your fields. If you wish to turn off automatic escaping, call the
4763 autoEscape() method with a false value immediately after creating the CGI object:
4766 $query->autoEscape(undef);
4769 =head2 CREATING AN ISINDEX TAG
4771 print $query->isindex(-action=>$action);
4775 print $query->isindex($action);
4777 Prints out an <ISINDEX> tag. Not very exciting. The parameter
4778 -action specifies the URL of the script to process the query. The
4779 default is to process the query with the current script.
4781 =head2 STARTING AND ENDING A FORM
4783 print $query->startform(-method=>$method,
4785 -enctype=>$encoding);
4786 <... various form stuff ...>
4787 print $query->endform;
4791 print $query->startform($method,$action,$encoding);
4792 <... various form stuff ...>
4793 print $query->endform;
4795 startform() will return a <FORM> tag with the optional method,
4796 action and form encoding that you specify. The defaults are:
4800 enctype: application/x-www-form-urlencoded
4802 endform() returns the closing </FORM> tag.
4804 Startform()'s enctype argument tells the browser how to package the various
4805 fields of the form before sending the form to the server. Two
4806 values are possible:
4810 =item B<application/x-www-form-urlencoded>
4812 This is the older type of encoding used by all browsers prior to
4813 Netscape 2.0. It is compatible with many CGI scripts and is
4814 suitable for short fields containing text data. For your
4815 convenience, CGI.pm stores the name of this encoding
4816 type in B<$CGI::URL_ENCODED>.
4818 =item B<multipart/form-data>
4820 This is the newer type of encoding introduced by Netscape 2.0.
4821 It is suitable for forms that contain very large fields or that
4822 are intended for transferring binary data. Most importantly,
4823 it enables the "file upload" feature of Netscape 2.0 forms. For
4824 your convenience, CGI.pm stores the name of this encoding type
4825 in B<&CGI::MULTIPART>
4827 Forms that use this type of encoding are not easily interpreted
4828 by CGI scripts unless they use CGI.pm or another library designed
4833 For compatibility, the startform() method uses the older form of
4834 encoding by default. If you want to use the newer form of encoding
4835 by default, you can call B<start_multipart_form()> instead of
4838 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
4839 for use with JavaScript. The -name parameter gives the
4840 form a name so that it can be identified and manipulated by
4841 JavaScript functions. -onSubmit should point to a JavaScript
4842 function that will be executed just before the form is submitted to your
4843 server. You can use this opportunity to check the contents of the form
4844 for consistency and completeness. If you find something wrong, you
4845 can put up an alert box or maybe fix things up yourself. You can
4846 abort the submission by returning false from this function.
4848 Usually the bulk of JavaScript functions are defined in a <SCRIPT>
4849 block in the HTML header and -onSubmit points to one of these function
4850 call. See start_html() for details.
4852 =head2 CREATING A TEXT FIELD
4854 print $query->textfield(-name=>'field_name',
4855 -default=>'starting value',
4860 print $query->textfield('field_name','starting value',50,80);
4862 textfield() will return a text input field.
4870 The first parameter is the required name for the field (-name).
4874 The optional second parameter is the default starting value for the field
4875 contents (-default).
4879 The optional third parameter is the size of the field in
4884 The optional fourth parameter is the maximum number of characters the
4885 field will accept (-maxlength).
4889 As with all these methods, the field will be initialized with its
4890 previous contents from earlier invocations of the script.
4891 When the form is processed, the value of the text field can be
4894 $value = $query->param('foo');
4896 If you want to reset it from its initial value after the script has been
4897 called once, you can do so like this:
4899 $query->param('foo',"I'm taking over this value!");
4901 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
4902 value, you can force its current value by using the -override (alias -force)
4905 print $query->textfield(-name=>'field_name',
4906 -default=>'starting value',
4911 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
4912 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
4913 parameters to register JavaScript event handlers. The onChange
4914 handler will be called whenever the user changes the contents of the
4915 text field. You can do text validation if you like. onFocus and
4916 onBlur are called respectively when the insertion point moves into and
4917 out of the text field. onSelect is called when the user changes the
4918 portion of the text that is selected.
4920 =head2 CREATING A BIG TEXT FIELD
4922 print $query->textarea(-name=>'foo',
4923 -default=>'starting value',
4929 print $query->textarea('foo','starting value',10,50);
4931 textarea() is just like textfield, but it allows you to specify
4932 rows and columns for a multiline text entry box. You can provide
4933 a starting value for the field, which can be long and contain
4936 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
4937 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
4938 recognized. See textfield().
4940 =head2 CREATING A PASSWORD FIELD
4942 print $query->password_field(-name=>'secret',
4943 -value=>'starting value',
4948 print $query->password_field('secret','starting value',50,80);
4950 password_field() is identical to textfield(), except that its contents
4951 will be starred out on the web page.
4953 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
4954 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
4955 recognized. See textfield().
4957 =head2 CREATING A FILE UPLOAD FIELD
4959 print $query->filefield(-name=>'uploaded_file',
4960 -default=>'starting value',
4965 print $query->filefield('uploaded_file','starting value',50,80);
4967 filefield() will return a file upload field for Netscape 2.0 browsers.
4968 In order to take full advantage of this I<you must use the new
4969 multipart encoding scheme> for the form. You can do this either
4970 by calling B<startform()> with an encoding type of B<$CGI::MULTIPART>,
4971 or by calling the new method B<start_multipart_form()> instead of
4972 vanilla B<startform()>.
4980 The first parameter is the required name for the field (-name).
4984 The optional second parameter is the starting value for the field contents
4985 to be used as the default file name (-default).
4987 For security reasons, browsers don't pay any attention to this field,
4988 and so the starting value will always be blank. Worse, the field
4989 loses its "sticky" behavior and forgets its previous contents. The
4990 starting value field is called for in the HTML specification, however,
4991 and possibly some browser will eventually provide support for it.
4995 The optional third parameter is the size of the field in
5000 The optional fourth parameter is the maximum number of characters the
5001 field will accept (-maxlength).
5005 When the form is processed, you can retrieve the entered filename
5008 $filename = $query->param('uploaded_file');
5010 Different browsers will return slightly different things for the
5011 name. Some browsers return the filename only. Others return the full
5012 path to the file, using the path conventions of the user's machine.
5013 Regardless, the name returned is always the name of the file on the
5014 I<user's> machine, and is unrelated to the name of the temporary file
5015 that CGI.pm creates during upload spooling (see below).
5017 The filename returned is also a file handle. You can read the contents
5018 of the file using standard Perl file reading calls:
5020 # Read a text file and print it out
5021 while (<$filename>) {
5025 # Copy a binary file to somewhere safe
5026 open (OUTFILE,">>/usr/local/web/users/feedback");
5027 while ($bytesread=read($filename,$buffer,1024)) {
5028 print OUTFILE $buffer;
5031 However, there are problems with the dual nature of the upload fields.
5032 If you C<use strict>, then Perl will complain when you try to use a
5033 string as a filehandle. You can get around this by placing the file
5034 reading code in a block containing the C<no strict> pragma. More
5035 seriously, it is possible for the remote user to type garbage into the
5036 upload field, in which case what you get from param() is not a
5037 filehandle at all, but a string.
5039 To be safe, use the I<upload()> function (new in version 2.47). When
5040 called with the name of an upload field, I<upload()> returns a
5041 filehandle, or undef if the parameter is not a valid filehandle.
5043 $fh = $query->upload('uploaded_file');
5048 This is the recommended idiom.
5050 When a file is uploaded the browser usually sends along some
5051 information along with it in the format of headers. The information
5052 usually includes the MIME content type. Future browsers may send
5053 other information as well (such as modification date and size). To
5054 retrieve this information, call uploadInfo(). It returns a reference to
5055 an associative array containing all the document headers.
5057 $filename = $query->param('uploaded_file');
5058 $type = $query->uploadInfo($filename)->{'Content-Type'};
5059 unless ($type eq 'text/html') {
5060 die "HTML FILES ONLY!";
5063 If you are using a machine that recognizes "text" and "binary" data
5064 modes, be sure to understand when and how to use them (see the Camel book).
5065 Otherwise you may find that binary files are corrupted during file
5068 There are occasionally problems involving parsing the uploaded file.
5069 This usually happens when the user presses "Stop" before the upload is
5070 finished. In this case, CGI.pm will return undef for the name of the
5071 uploaded file and set I<cgi_error()> to the string "400 Bad request
5072 (malformed multipart POST)". This error message is designed so that
5073 you can incorporate it into a status code to be sent to the browser.
5076 $file = $query->upload('uploaded_file');
5077 if (!$file && $query->cgi_error) {
5078 print $query->header(-status->$query->cgi_error);
5082 You are free to create a custom HTML page to complain about the error,
5085 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5086 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5087 recognized. See textfield() for details.
5089 =head2 CREATING A POPUP MENU
5091 print $query->popup_menu('menu_name',
5092 ['eenie','meenie','minie'],
5097 %labels = ('eenie'=>'your first choice',
5098 'meenie'=>'your second choice',
5099 'minie'=>'your third choice');
5100 print $query->popup_menu('menu_name',
5101 ['eenie','meenie','minie'],
5104 -or (named parameter style)-
5106 print $query->popup_menu(-name=>'menu_name',
5107 -values=>['eenie','meenie','minie'],
5111 popup_menu() creates a menu.
5117 The required first argument is the menu's name (-name).
5121 The required second argument (-values) is an array B<reference>
5122 containing the list of menu items in the menu. You can pass the
5123 method an anonymous array, as shown in the example, or a reference to
5124 a named array, such as "\@foo".
5128 The optional third parameter (-default) is the name of the default
5129 menu choice. If not specified, the first item will be the default.
5130 The values of the previous choice will be maintained across queries.
5134 The optional fourth parameter (-labels) is provided for people who
5135 want to use different values for the user-visible label inside the
5136 popup menu nd the value returned to your script. It's a pointer to an
5137 associative array relating menu values to user-visible labels. If you
5138 leave this parameter blank, the menu values will be displayed by
5139 default. (You can also leave a label undefined if you want to).
5143 When the form is processed, the selected value of the popup menu can
5146 $popup_menu_value = $query->param('menu_name');
5148 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
5149 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5150 B<-onBlur>. See the textfield() section for details on when these
5151 handlers are called.
5153 =head2 CREATING A SCROLLING LIST
5155 print $query->scrolling_list('list_name',
5156 ['eenie','meenie','minie','moe'],
5157 ['eenie','moe'],5,'true');
5160 print $query->scrolling_list('list_name',
5161 ['eenie','meenie','minie','moe'],
5162 ['eenie','moe'],5,'true',
5167 print $query->scrolling_list(-name=>'list_name',
5168 -values=>['eenie','meenie','minie','moe'],
5169 -default=>['eenie','moe'],
5174 scrolling_list() creates a scrolling list.
5178 =item B<Parameters:>
5182 The first and second arguments are the list name (-name) and values
5183 (-values). As in the popup menu, the second argument should be an
5188 The optional third argument (-default) can be either a reference to a
5189 list containing the values to be selected by default, or can be a
5190 single value to select. If this argument is missing or undefined,
5191 then nothing is selected when the list first appears. In the named
5192 parameter version, you can use the synonym "-defaults" for this
5197 The optional fourth argument is the size of the list (-size).
5201 The optional fifth argument can be set to true to allow multiple
5202 simultaneous selections (-multiple). Otherwise only one selection
5203 will be allowed at a time.
5207 The optional sixth argument is a pointer to an associative array
5208 containing long user-visible labels for the list items (-labels).
5209 If not provided, the values will be displayed.
5211 When this form is processed, all selected list items will be returned as
5212 a list under the parameter name 'list_name'. The values of the
5213 selected items can be retrieved with:
5215 @selected = $query->param('list_name');
5219 JAVASCRIPTING: scrolling_list() recognizes the following event
5220 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5221 and B<-onBlur>. See textfield() for the description of when these
5222 handlers are called.
5224 =head2 CREATING A GROUP OF RELATED CHECKBOXES
5226 print $query->checkbox_group(-name=>'group_name',
5227 -values=>['eenie','meenie','minie','moe'],
5228 -default=>['eenie','moe'],
5232 print $query->checkbox_group('group_name',
5233 ['eenie','meenie','minie','moe'],
5234 ['eenie','moe'],'true',\%labels);
5236 HTML3-COMPATIBLE BROWSERS ONLY:
5238 print $query->checkbox_group(-name=>'group_name',
5239 -values=>['eenie','meenie','minie','moe'],
5240 -rows=2,-columns=>2);
5243 checkbox_group() creates a list of checkboxes that are related
5248 =item B<Parameters:>
5252 The first and second arguments are the checkbox name and values,
5253 respectively (-name and -values). As in the popup menu, the second
5254 argument should be an array reference. These values are used for the
5255 user-readable labels printed next to the checkboxes as well as for the
5256 values passed to your script in the query string.
5260 The optional third argument (-default) can be either a reference to a
5261 list containing the values to be checked by default, or can be a
5262 single value to checked. If this argument is missing or undefined,
5263 then nothing is selected when the list first appears.
5267 The optional fourth argument (-linebreak) can be set to true to place
5268 line breaks between the checkboxes so that they appear as a vertical
5269 list. Otherwise, they will be strung together on a horizontal line.
5273 The optional fifth argument is a pointer to an associative array
5274 relating the checkbox values to the user-visible labels that will
5275 be printed next to them (-labels). If not provided, the values will
5276 be used as the default.
5280 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5281 the optional parameters B<-rows>, and B<-columns>. These parameters
5282 cause checkbox_group() to return an HTML3 compatible table containing
5283 the checkbox group formatted with the specified number of rows and
5284 columns. You can provide just the -columns parameter if you wish;
5285 checkbox_group will calculate the correct number of rows for you.
5287 To include row and column headings in the returned table, you
5288 can use the B<-rowheaders> and B<-colheaders> parameters. Both
5289 of these accept a pointer to an array of headings to use.
5290 The headings are just decorative. They don't reorganize the
5291 interpretation of the checkboxes -- they're still a single named
5296 When the form is processed, all checked boxes will be returned as
5297 a list under the parameter name 'group_name'. The values of the
5298 "on" checkboxes can be retrieved with:
5300 @turned_on = $query->param('group_name');
5302 The value returned by checkbox_group() is actually an array of button
5303 elements. You can capture them and use them within tables, lists,
5304 or in other creative ways:
5306 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
5307 &use_in_creative_way(@h);
5309 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
5310 parameter. This specifies a JavaScript code fragment or
5311 function call to be executed every time the user clicks on
5312 any of the buttons in the group. You can retrieve the identity
5313 of the particular button clicked on using the "this" variable.
5315 =head2 CREATING A STANDALONE CHECKBOX
5317 print $query->checkbox(-name=>'checkbox_name',
5318 -checked=>'checked',
5320 -label=>'CLICK ME');
5324 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
5326 checkbox() is used to create an isolated checkbox that isn't logically
5327 related to any others.
5331 =item B<Parameters:>
5335 The first parameter is the required name for the checkbox (-name). It
5336 will also be used for the user-readable label printed next to the
5341 The optional second parameter (-checked) specifies that the checkbox
5342 is turned on by default. Synonyms are -selected and -on.
5346 The optional third parameter (-value) specifies the value of the
5347 checkbox when it is checked. If not provided, the word "on" is
5352 The optional fourth parameter (-label) is the user-readable label to
5353 be attached to the checkbox. If not provided, the checkbox name is
5358 The value of the checkbox can be retrieved using:
5360 $turned_on = $query->param('checkbox_name');
5362 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
5363 parameter. See checkbox_group() for further details.
5365 =head2 CREATING A RADIO BUTTON GROUP
5367 print $query->radio_group(-name=>'group_name',
5368 -values=>['eenie','meenie','minie'],
5375 print $query->radio_group('group_name',['eenie','meenie','minie'],
5376 'meenie','true',\%labels);
5379 HTML3-COMPATIBLE BROWSERS ONLY:
5381 print $query->radio_group(-name=>'group_name',
5382 -values=>['eenie','meenie','minie','moe'],
5383 -rows=2,-columns=>2);
5385 radio_group() creates a set of logically-related radio buttons
5386 (turning one member of the group on turns the others off)
5390 =item B<Parameters:>
5394 The first argument is the name of the group and is required (-name).
5398 The second argument (-values) is the list of values for the radio
5399 buttons. The values and the labels that appear on the page are
5400 identical. Pass an array I<reference> in the second argument, either
5401 using an anonymous array, as shown, or by referencing a named array as
5406 The optional third parameter (-default) is the name of the default
5407 button to turn on. If not specified, the first item will be the
5408 default. You can provide a nonexistent button name, such as "-" to
5409 start up with no buttons selected.
5413 The optional fourth parameter (-linebreak) can be set to 'true' to put
5414 line breaks between the buttons, creating a vertical list.
5418 The optional fifth parameter (-labels) is a pointer to an associative
5419 array relating the radio button values to user-visible labels to be
5420 used in the display. If not provided, the values themselves are
5425 B<HTML3-compatible browsers> (such as Netscape) can take advantage
5427 parameters B<-rows>, and B<-columns>. These parameters cause
5428 radio_group() to return an HTML3 compatible table containing
5429 the radio group formatted with the specified number of rows
5430 and columns. You can provide just the -columns parameter if you
5431 wish; radio_group will calculate the correct number of rows
5434 To include row and column headings in the returned table, you
5435 can use the B<-rowheader> and B<-colheader> parameters. Both
5436 of these accept a pointer to an array of headings to use.
5437 The headings are just decorative. They don't reorganize the
5438 interpretation of the radio buttons -- they're still a single named
5443 When the form is processed, the selected radio button can
5446 $which_radio_button = $query->param('group_name');
5448 The value returned by radio_group() is actually an array of button
5449 elements. You can capture them and use them within tables, lists,
5450 or in other creative ways:
5452 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
5453 &use_in_creative_way(@h);
5455 =head2 CREATING A SUBMIT BUTTON
5457 print $query->submit(-name=>'button_name',
5462 print $query->submit('button_name','value');
5464 submit() will create the query submission button. Every form
5465 should have one of these.
5469 =item B<Parameters:>
5473 The first argument (-name) is optional. You can give the button a
5474 name if you have several submission buttons in your form and you want
5475 to distinguish between them. The name will also be used as the
5476 user-visible label. Be aware that a few older browsers don't deal with this correctly and
5477 B<never> send back a value from a button.
5481 The second argument (-value) is also optional. This gives the button
5482 a value that will be passed to your script in the query string.
5486 You can figure out which button was pressed by using different
5487 values for each one:
5489 $which_one = $query->param('button_name');
5491 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
5492 parameter. See checkbox_group() for further details.
5494 =head2 CREATING A RESET BUTTON
5498 reset() creates the "reset" button. Note that it restores the
5499 form to its value from the last time the script was called,
5500 NOT necessarily to the defaults.
5502 Note that this conflicts with the Perl reset() built-in. Use
5503 CORE::reset() to get the original reset function.
5505 =head2 CREATING A DEFAULT BUTTON
5507 print $query->defaults('button_label')
5509 defaults() creates a button that, when invoked, will cause the
5510 form to be completely reset to its defaults, wiping out all the
5511 changes the user ever made.
5513 =head2 CREATING A HIDDEN FIELD
5515 print $query->hidden(-name=>'hidden_name',
5516 -default=>['value1','value2'...]);
5520 print $query->hidden('hidden_name','value1','value2'...);
5522 hidden() produces a text field that can't be seen by the user. It
5523 is useful for passing state variable information from one invocation
5524 of the script to the next.
5528 =item B<Parameters:>
5532 The first argument is required and specifies the name of this
5537 The second argument is also required and specifies its value
5538 (-default). In the named parameter style of calling, you can provide
5539 a single value here or a reference to a whole list
5543 Fetch the value of a hidden field this way:
5545 $hidden_value = $query->param('hidden_name');
5547 Note, that just like all the other form elements, the value of a
5548 hidden field is "sticky". If you want to replace a hidden field with
5549 some other values after the script has been called once you'll have to
5552 $query->param('hidden_name','new','values','here');
5554 =head2 CREATING A CLICKABLE IMAGE BUTTON
5556 print $query->image_button(-name=>'button_name',
5557 -src=>'/source/URL',
5562 print $query->image_button('button_name','/source/URL','MIDDLE');
5564 image_button() produces a clickable image. When it's clicked on the
5565 position of the click is returned to your script as "button_name.x"
5566 and "button_name.y", where "button_name" is the name you've assigned
5569 JAVASCRIPTING: image_button() recognizes the B<-onClick>
5570 parameter. See checkbox_group() for further details.
5574 =item B<Parameters:>
5578 The first argument (-name) is required and specifies the name of this
5583 The second argument (-src) is also required and specifies the URL
5586 The third option (-align, optional) is an alignment type, and may be
5587 TOP, BOTTOM or MIDDLE
5591 Fetch the value of the button this way:
5592 $x = $query->param('button_name.x');
5593 $y = $query->param('button_name.y');
5595 =head2 CREATING A JAVASCRIPT ACTION BUTTON
5597 print $query->button(-name=>'button_name',
5598 -value=>'user visible label',
5599 -onClick=>"do_something()");
5603 print $query->button('button_name',"do_something()");
5605 button() produces a button that is compatible with Netscape 2.0's
5606 JavaScript. When it's pressed the fragment of JavaScript code
5607 pointed to by the B<-onClick> parameter will be executed. On
5608 non-Netscape browsers this form element will probably not even
5613 Netscape browsers versions 1.1 and higher, and all versions of
5614 Internet Explorer, support a so-called "cookie" designed to help
5615 maintain state within a browser session. CGI.pm has several methods
5616 that support cookies.
5618 A cookie is a name=value pair much like the named parameters in a CGI
5619 query string. CGI scripts create one or more cookies and send
5620 them to the browser in the HTTP header. The browser maintains a list
5621 of cookies that belong to a particular Web server, and returns them
5622 to the CGI script during subsequent interactions.
5624 In addition to the required name=value pair, each cookie has several
5625 optional attributes:
5629 =item 1. an expiration time
5631 This is a time/date string (in a special GMT format) that indicates
5632 when a cookie expires. The cookie will be saved and returned to your
5633 script until this expiration date is reached if the user exits
5634 the browser and restarts it. If an expiration date isn't specified, the cookie
5635 will remain active until the user quits the browser.
5639 This is a partial or complete domain name for which the cookie is
5640 valid. The browser will return the cookie to any host that matches
5641 the partial domain name. For example, if you specify a domain name
5642 of ".capricorn.com", then the browser will return the cookie to
5643 Web servers running on any of the machines "www.capricorn.com",
5644 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
5645 must contain at least two periods to prevent attempts to match
5646 on top level domains like ".edu". If no domain is specified, then
5647 the browser will only return the cookie to servers on the host the
5648 cookie originated from.
5652 If you provide a cookie path attribute, the browser will check it
5653 against your script's URL before returning the cookie. For example,
5654 if you specify the path "/cgi-bin", then the cookie will be returned
5655 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
5656 and "/cgi-bin/customer_service/complain.pl", but not to the script
5657 "/cgi-private/site_admin.pl". By default, path is set to "/", which
5658 causes the cookie to be sent to any CGI script on your site.
5660 =item 4. a "secure" flag
5662 If the "secure" attribute is set, the cookie will only be sent to your
5663 script if the CGI request is occurring on a secure channel, such as SSL.
5667 The interface to HTTP cookies is the B<cookie()> method:
5669 $cookie = $query->cookie(-name=>'sessionID',
5672 -path=>'/cgi-bin/database',
5673 -domain=>'.capricorn.org',
5675 print $query->header(-cookie=>$cookie);
5677 B<cookie()> creates a new cookie. Its parameters include:
5683 The name of the cookie (required). This can be any string at all.
5684 Although browsers limit their cookie names to non-whitespace
5685 alphanumeric characters, CGI.pm removes this restriction by escaping
5686 and unescaping cookies behind the scenes.
5690 The value of the cookie. This can be any scalar value,
5691 array reference, or even associative array reference. For example,
5692 you can store an entire associative array into a cookie this way:
5694 $cookie=$query->cookie(-name=>'family information',
5695 -value=>\%childrens_ages);
5699 The optional partial path for which this cookie will be valid, as described
5704 The optional partial domain for which this cookie will be valid, as described
5709 The optional expiration date for this cookie. The format is as described
5710 in the section on the B<header()> method:
5712 "+1h" one hour from now
5716 If set to true, this cookie will only be used within a secure
5721 The cookie created by cookie() must be incorporated into the HTTP
5722 header within the string returned by the header() method:
5724 print $query->header(-cookie=>$my_cookie);
5726 To create multiple cookies, give header() an array reference:
5728 $cookie1 = $query->cookie(-name=>'riddle_name',
5729 -value=>"The Sphynx's Question");
5730 $cookie2 = $query->cookie(-name=>'answers',
5732 print $query->header(-cookie=>[$cookie1,$cookie2]);
5734 To retrieve a cookie, request it by name by calling cookie()
5735 method without the B<-value> parameter:
5739 %answers = $query->cookie(-name=>'answers');
5740 # $query->cookie('answers') will work too!
5742 The cookie and CGI namespaces are separate. If you have a parameter
5743 named 'answers' and a cookie named 'answers', the values retrieved by
5744 param() and cookie() are independent of each other. However, it's
5745 simple to turn a CGI parameter into a cookie, and vice-versa:
5747 # turn a CGI parameter into a cookie
5748 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
5750 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
5752 See the B<cookie.cgi> example script for some ideas on how to use
5753 cookies effectively.
5755 =head1 WORKING WITH FRAMES
5757 It's possible for CGI.pm scripts to write into several browser panels
5758 and windows using the HTML 4 frame mechanism. There are three
5759 techniques for defining new frames programmatically:
5763 =item 1. Create a <Frameset> document
5765 After writing out the HTTP header, instead of creating a standard
5766 HTML document using the start_html() call, create a <FRAMESET>
5767 document that defines the frames on the page. Specify your script(s)
5768 (with appropriate parameters) as the SRC for each of the frames.
5770 There is no specific support for creating <FRAMESET> sections
5771 in CGI.pm, but the HTML is very simple to write. See the frame
5772 documentation in Netscape's home pages for details
5774 http://home.netscape.com/assist/net_sites/frames.html
5776 =item 2. Specify the destination for the document in the HTTP header
5778 You may provide a B<-target> parameter to the header() method:
5780 print $q->header(-target=>'ResultsWindow');
5782 This will tell the browser to load the output of your script into the
5783 frame named "ResultsWindow". If a frame of that name doesn't already
5784 exist, the browser will pop up a new window and load your script's
5785 document into that. There are a number of magic names that you can
5786 use for targets. See the frame documents on Netscape's home pages for
5789 =item 3. Specify the destination for the document in the <FORM> tag
5791 You can specify the frame to load in the FORM tag itself. With
5792 CGI.pm it looks like this:
5794 print $q->startform(-target=>'ResultsWindow');
5796 When your script is reinvoked by the form, its output will be loaded
5797 into the frame named "ResultsWindow". If one doesn't already exist
5798 a new window will be created.
5802 The script "frameset.cgi" in the examples directory shows one way to
5803 create pages in which the fill-out form and the response live in
5804 side-by-side frames.
5806 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
5808 CGI.pm has limited support for HTML3's cascading style sheets (css).
5809 To incorporate a stylesheet into your document, pass the
5810 start_html() method a B<-style> parameter. The value of this
5811 parameter may be a scalar, in which case it is incorporated directly
5812 into a <STYLE> section, or it may be a hash reference. In the latter
5813 case you should provide the hash with one or more of B<-src> or
5814 B<-code>. B<-src> points to a URL where an externally-defined
5815 stylesheet can be found. B<-code> points to a scalar value to be
5816 incorporated into a <STYLE> section. Style definitions in B<-code>
5817 override similarly-named ones in B<-src>, hence the name "cascading."
5819 You may also specify the type of the stylesheet by adding the optional
5820 B<-type> parameter to the hash pointed to by B<-style>. If not
5821 specified, the style defaults to 'text/css'.
5823 To refer to a style within the body of your document, add the
5824 B<-class> parameter to any HTML element:
5826 print h1({-class=>'Fancy'},'Welcome to the Party');
5828 Or define styles on the fly with the B<-style> parameter:
5830 print h1({-style=>'Color: red;'},'Welcome to Hell');
5832 You may also use the new B<span()> element to apply a style to a
5835 print span({-style=>'Color: red;'},
5836 h1('Welcome to Hell'),
5837 "Where did that handbasket get to?"
5840 Note that you must import the ":html3" definitions to have the
5841 B<span()> method available. Here's a quick and dirty example of using
5842 CSS's. See the CSS specification at
5843 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
5845 use CGI qw/:standard :html3/;
5847 #here's a stylesheet incorporated directly into the page
5857 font-family: sans-serif;
5863 print start_html( -title=>'CGI with Style',
5864 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
5867 print h1('CGI with Style'),
5869 "Better read the cascading style sheet spec before playing with this!"),
5870 span({-style=>'color: magenta'},
5871 "Look Mom, no hands!",
5879 If you are running the script
5880 from the command line or in the perl debugger, you can pass the script
5881 a list of keywords or parameter=value pairs on the command line or
5882 from standard input (you don't have to worry about tricking your
5883 script into reading from environment variables).
5884 You can pass keywords like this:
5886 your_script.pl keyword1 keyword2 keyword3
5890 your_script.pl keyword1+keyword2+keyword3
5894 your_script.pl name1=value1 name2=value2
5898 your_script.pl name1=value1&name2=value2
5900 or even as newline-delimited parameters on standard input.
5902 When debugging, you can use quotes and backslashes to escape
5903 characters in the familiar shell manner, letting you place
5904 spaces and other funny characters in your parameter=value
5907 your_script.pl "name1='I am a long value'" "name2=two\ words"
5909 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
5911 The dump() method produces a string consisting of all the query's
5912 name/value pairs formatted nicely as a nested list. This is useful
5913 for debugging purposes:
5918 Produces something that looks like:
5932 As a shortcut, you can interpolate the entire CGI object into a string
5933 and it will be replaced with the a nice HTML dump shown above:
5936 print "<H2>Current Values</H2> $query\n";
5938 =head1 FETCHING ENVIRONMENT VARIABLES
5940 Some of the more useful environment variables can be fetched
5941 through this interface. The methods are as follows:
5947 Return a list of MIME types that the remote browser accepts. If you
5948 give this method a single argument corresponding to a MIME type, as in
5949 $query->Accept('text/html'), it will return a floating point value
5950 corresponding to the browser's preference for this type from 0.0
5951 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
5952 list are handled correctly.
5954 Note that the capitalization changed between version 2.43 and 2.44 in
5955 order to avoid conflict with Perl's accept() function.
5957 =item B<raw_cookie()>
5959 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
5960 Netscape browsers version 1.1 and higher, and all versions of Internet
5961 Explorer. Cookies have a special format, and this method call just
5962 returns the raw form (?cookie dough). See cookie() for ways of
5963 setting and retrieving cooked cookies.
5965 Called with no parameters, raw_cookie() returns the packed cookie
5966 structure. You can separate it into individual cookies by splitting
5967 on the character sequence "; ". Called with the name of a cookie,
5968 retrieves the B<unescaped> form of the cookie. You can use the
5969 regular cookie() method to get the names, or use the raw_fetch()
5970 method from the CGI::Cookie module.
5972 =item B<user_agent()>
5974 Returns the HTTP_USER_AGENT variable. If you give
5975 this method a single argument, it will attempt to
5976 pattern match on it, allowing you to do something
5977 like $query->user_agent(netscape);
5979 =item B<path_info()>
5981 Returns additional path information from the script URL.
5982 E.G. fetching /cgi-bin/your_script/additional/stuff will
5983 result in $query->path_info() returning
5986 NOTE: The Microsoft Internet Information Server
5987 is broken with respect to additional path information. If
5988 you use the Perl DLL library, the IIS server will attempt to
5989 execute the additional path information as a Perl script.
5990 If you use the ordinary file associations mapping, the
5991 path information will be present in the environment,
5992 but incorrect. The best thing to do is to avoid using additional
5993 path information in CGI scripts destined for use with IIS.
5995 =item B<path_translated()>
5997 As per path_info() but returns the additional
5998 path information translated into a physical path, e.g.
5999 "/usr/local/etc/httpd/htdocs/additional/stuff".
6001 The Microsoft IIS is broken with respect to the translated
6004 =item B<remote_host()>
6006 Returns either the remote host name or IP address.
6007 if the former is unavailable.
6009 =item B<script_name()>
6010 Return the script name as a partial URL, for self-refering
6015 Return the URL of the page the browser was viewing
6016 prior to fetching your script. Not available for all
6019 =item B<auth_type ()>
6021 Return the authorization/verification method in use for this
6024 =item B<server_name ()>
6026 Returns the name of the server, usually the machine's host
6029 =item B<virtual_host ()>
6031 When using virtual hosts, returns the name of the host that
6032 the browser attempted to contact
6034 =item B<server_software ()>
6036 Returns the server software and version number.
6038 =item B<remote_user ()>
6040 Return the authorization/verification name used for user
6041 verification, if this script is protected.
6043 =item B<user_name ()>
6045 Attempt to obtain the remote user's name, using a variety of different
6046 techniques. This only works with older browsers such as Mosaic.
6047 Newer browsers do not report the user name for privacy reasons!
6049 =item B<request_method()>
6051 Returns the method used to access your script, usually
6052 one of 'POST', 'GET' or 'HEAD'.
6054 =item B<content_type()>
6056 Returns the content_type of data submitted in a POST, generally
6057 multipart/form-data or application/x-www-form-urlencoded
6061 Called with no arguments returns the list of HTTP environment
6062 variables, including such things as HTTP_USER_AGENT,
6063 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6064 like-named HTTP header fields in the request. Called with the name of
6065 an HTTP header field, returns its value. Capitalization and the use
6066 of hyphens versus underscores are not significant.
6068 For example, all three of these examples are equivalent:
6070 $requested_language = $q->http('Accept-language');
6071 $requested_language = $q->http('Accept_language');
6072 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6076 The same as I<http()>, but operates on the HTTPS environment variables
6077 present when the SSL protocol is in effect. Can be used to determine
6078 whether SSL is turned on.
6082 =head1 USING NPH SCRIPTS
6084 NPH, or "no-parsed-header", scripts bypass the server completely by
6085 sending the complete HTTP header directly to the browser. This has
6086 slight performance benefits, but is of most use for taking advantage
6087 of HTTP extensions that are not directly supported by your server,
6088 such as server push and PICS headers.
6090 Servers use a variety of conventions for designating CGI scripts as
6091 NPH. Many Unix servers look at the beginning of the script's name for
6092 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
6093 Internet Information Server, in contrast, try to decide whether a
6094 program is an NPH script by examining the first line of script output.
6097 CGI.pm supports NPH scripts with a special NPH mode. When in this
6098 mode, CGI.pm will output the necessary extra header information when
6099 the header() and redirect() methods are
6102 The Microsoft Internet Information Server requires NPH mode. As of version
6103 2.30, CGI.pm will automatically detect when the script is running under IIS
6104 and put itself into this mode. You do not need to do this manually, although
6105 it won't hurt anything if you do.
6107 There are a number of ways to put CGI.pm into NPH mode:
6111 =item In the B<use> statement
6113 Simply add the "-nph" pragmato the list of symbols to be imported into
6116 use CGI qw(:standard -nph)
6118 =item By calling the B<nph()> method:
6120 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
6124 =item By using B<-nph> parameters in the B<header()> and B<redirect()> statements:
6126 print $q->header(-nph=>1);
6132 CGI.pm provides three simple functions for producing multipart
6133 documents of the type needed to implement server push. These
6134 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
6135 import these into your namespace, you must import the ":push" set.
6136 You are also advised to put the script into NPH mode and to set $| to
6137 1 to avoid buffering problems.
6139 Here is a simple script that demonstrates server push:
6141 #!/usr/local/bin/perl
6142 use CGI qw/:push -nph/;
6144 print multipart_init(-boundary=>'----------------here we go!');
6146 print multipart_start(-type=>'text/plain'),
6147 "The current time is ",scalar(localtime),"\n",
6152 This script initializes server push by calling B<multipart_init()>.
6153 It then enters an infinite loop in which it begins a new multipart
6154 section by calling B<multipart_start()>, prints the current local time,
6155 and ends a multipart section with B<multipart_end()>. It then sleeps
6156 a second, and begins again.
6160 =item multipart_init()
6162 multipart_init(-boundary=>$boundary);
6164 Initialize the multipart system. The -boundary argument specifies
6165 what MIME boundary string to use to separate parts of the document.
6166 If not provided, CGI.pm chooses a reasonable boundary for you.
6168 =item multipart_start()
6170 multipart_start(-type=>$type)
6172 Start a new part of the multipart document using the specified MIME
6173 type. If not specified, text/html is assumed.
6175 =item multipart_end()
6179 End a part. You must remember to call multipart_end() once for each
6184 Users interested in server push applications should also have a look
6185 at the CGI::Push module.
6187 =head1 Avoiding Denial of Service Attacks
6189 A potential problem with CGI.pm is that, by default, it attempts to
6190 process form POSTings no matter how large they are. A wily hacker
6191 could attack your site by sending a CGI script a huge POST of many
6192 megabytes. CGI.pm will attempt to read the entire POST into a
6193 variable, growing hugely in size until it runs out of memory. While
6194 the script attempts to allocate the memory the system may slow down
6195 dramatically. This is a form of denial of service attack.
6197 Another possible attack is for the remote user to force CGI.pm to
6198 accept a huge file upload. CGI.pm will accept the upload and store it
6199 in a temporary directory even if your script doesn't expect to receive
6200 an uploaded file. CGI.pm will delete the file automatically when it
6201 terminates, but in the meantime the remote user may have filled up the
6202 server's disk space, causing problems for other programs.
6204 The best way to avoid denial of service attacks is to limit the amount
6205 of memory, CPU time and disk space that CGI scripts can use. Some Web
6206 servers come with built-in facilities to accomplish this. In other
6207 cases, you can use the shell I<limit> or I<ulimit>
6208 commands to put ceilings on CGI resource usage.
6211 CGI.pm also has some simple built-in protections against denial of
6212 service attacks, but you must activate them before you can use them.
6213 These take the form of two global variables in the CGI name space:
6217 =item B<$CGI::POST_MAX>
6219 If set to a non-negative integer, this variable puts a ceiling
6220 on the size of POSTings, in bytes. If CGI.pm detects a POST
6221 that is greater than the ceiling, it will immediately exit with an error
6222 message. This value will affect both ordinary POSTs and
6223 multipart POSTs, meaning that it limits the maximum size of file
6224 uploads as well. You should set this to a reasonably high
6225 value, such as 1 megabyte.
6227 =item B<$CGI::DISABLE_UPLOADS>
6229 If set to a non-zero value, this will disable file uploads
6230 completely. Other fill-out form values will work as usual.
6234 You can use these variables in either of two ways.
6238 =item B<1. On a script-by-script basis>
6240 Set the variable at the top of the script, right after the "use" statement:
6242 use CGI qw/:standard/;
6243 use CGI::Carp 'fatalsToBrowser';
6244 $CGI::POST_MAX=1024 * 100; # max 100K posts
6245 $CGI::DISABLE_UPLOADS = 1; # no uploads
6247 =item B<2. Globally for all scripts>
6249 Open up CGI.pm, find the definitions for $POST_MAX and
6250 $DISABLE_UPLOADS, and set them to the desired values. You'll
6251 find them towards the top of the file in a subroutine named
6252 initialize_globals().
6256 An attempt to send a POST larger than $POST_MAX bytes will cause
6257 I<param()> to return an empty CGI parameter list. You can test for
6258 this event by checking I<cgi_error()>, either after you create the CGI
6259 object or, if you are using the function-oriented interface, call
6260 <param()> for the first time. If the POST was intercepted, then
6261 cgi_error() will return the message "413 POST too large".
6263 This error message is actually defined by the HTTP protocol, and is
6264 designed to be returned to the browser as the CGI script's status
6267 $uploaded_file = param('upload');
6268 if (!$uploaded_file && cgi_error()) {
6269 print header(-status=>cgi_error());
6273 However it isn't clear that any browser currently knows what to do
6274 with this status code. It might be better just to create an
6275 HTML page that warns the user of the problem.
6277 =head1 COMPATIBILITY WITH CGI-LIB.PL
6279 To make it easier to port existing programs that use cgi-lib.pl the
6280 compatibility routine "ReadParse" is provided. Porting is simple:
6283 require "cgi-lib.pl";
6285 print "The value of the antique is $in{antique}.\n";
6290 print "The value of the antique is $in{antique}.\n";
6292 CGI.pm's ReadParse() routine creates a tied variable named %in,
6293 which can be accessed to obtain the query variables. Like
6294 ReadParse, you can also provide your own variable. Infrequently
6295 used features of ReadParse, such as the creation of @in and $in
6296 variables, are not supported.
6298 Once you use ReadParse, you can retrieve the query object itself
6302 print $q->textfield(-name=>'wow',
6303 -value=>'does this really work?');
6305 This allows you to start using the more interesting features
6306 of CGI.pm without rewriting your old scripts from scratch.
6308 =head1 AUTHOR INFORMATION
6310 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
6312 This library is free software; you can redistribute it and/or modify
6313 it under the same terms as Perl itself.
6315 Address bug reports and comments to: lstein@cshl.org. When sending
6316 bug reports, please provide the version of CGI.pm, the version of
6317 Perl, the name and version of your Web server, and the name and
6318 version of the operating system you are using. If the problem is even
6319 remotely browser dependent, please provide information about the
6320 affected browers as well.
6324 Thanks very much to:
6328 =item Matt Heffron (heffron@falstaff.css.beckman.com)
6330 =item James Taylor (james.taylor@srs.gov)
6332 =item Scott Anguish <sanguish@digifix.com>
6334 =item Mike Jewell (mlj3u@virginia.edu)
6336 =item Timothy Shimmin (tes@kbs.citri.edu.au)
6338 =item Joergen Haegg (jh@axis.se)
6340 =item Laurent Delfosse (delfosse@delfosse.com)
6342 =item Richard Resnick (applepi1@aol.com)
6344 =item Craig Bishop (csb@barwonwater.vic.gov.au)
6346 =item Tony Curtis (tc@vcpc.univie.ac.at)
6348 =item Tim Bunce (Tim.Bunce@ig.co.uk)
6350 =item Tom Christiansen (tchrist@convex.com)
6352 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
6354 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
6356 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
6358 =item Stephen Dahmen (joyfire@inxpress.net)
6360 =item Ed Jordan (ed@fidalgo.net)
6362 =item David Alan Pisoni (david@cnation.com)
6364 =item Doug MacEachern (dougm@opengroup.org)
6366 =item Robin Houston (robin@oneworld.org)
6368 =item ...and many many more...
6370 for suggestions and bug fixes.
6374 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
6377 #!/usr/local/bin/perl
6383 print $query->header;
6384 print $query->start_html("Example CGI.pm Form");
6385 print "<H1> Example CGI.pm Form</H1>\n";
6386 &print_prompt($query);
6389 print $query->end_html;
6394 print $query->startform;
6395 print "<EM>What's your name?</EM><BR>";
6396 print $query->textfield('name');
6397 print $query->checkbox('Not my real name');
6399 print "<P><EM>Where can you find English Sparrows?</EM><BR>";
6400 print $query->checkbox_group(
6401 -name=>'Sparrow locations',
6402 -values=>[England,France,Spain,Asia,Hoboken],
6404 -defaults=>[England,Asia]);
6406 print "<P><EM>How far can they fly?</EM><BR>",
6407 $query->radio_group(
6409 -values=>['10 ft','1 mile','10 miles','real far'],
6410 -default=>'1 mile');
6412 print "<P><EM>What's your favorite color?</EM> ";
6413 print $query->popup_menu(-name=>'Color',
6414 -values=>['black','brown','red','yellow'],
6417 print $query->hidden('Reference','Monty Python and the Holy Grail');
6419 print "<P><EM>What have you got there?</EM><BR>";
6420 print $query->scrolling_list(
6421 -name=>'possessions',
6422 -values=>['A Coconut','A Grail','An Icon',
6423 'A Sword','A Ticket'],
6427 print "<P><EM>Any parting comments?</EM><BR>";
6428 print $query->textarea(-name=>'Comments',
6432 print "<P>",$query->Reset;
6433 print $query->submit('Action','Shout');
6434 print $query->submit('Action','Scream');
6435 print $query->endform;
6443 print "<H2>Here are the current settings in this form</H2>";
6445 foreach $key ($query->param) {
6446 print "<STRONG>$key</STRONG> -> ";
6447 @values = $query->param($key);
6448 print join(", ",@values),"<BR>\n";
6455 <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
6456 <A HREF="/">Home Page</A>
6462 This module has grown large and monolithic. Furthermore it's doing many
6463 things, such as handling URLs, parsing CGI input, writing HTML, etc., that
6464 are also done in the LWP modules. It should be discarded in favor of
6465 the CGI::* modules, but somehow I continue to work on it.
6467 Note that the code is truly contorted in order to avoid spurious
6468 warnings when programs are run with the B<-w> switch.
6472 L<CGI::Carp>, L<URI::URL>, L<CGI::Request>, L<CGI::MiniSvr>,
6473 L<CGI::Base>, L<CGI::Form>, L<CGI::Push>, L<CGI::Fast>,