5 # See the bottom of this file for the POD documentation. Search for the
8 # You can run this file through either pod2man or pod2html to produce pretty
9 # documentation in manual or html file format (these utilities are part of the
10 # Perl 5 distribution).
12 # Copyright 1995-1998 Lincoln D. Stein. All rights reserved.
13 # It may be used and modified freely, but I do request that this copyright
14 # notice remain attached to the file. You may modify this module as you
15 # wish, but if you redistribute a modified version, please attach a note
16 # listing the modifications you have made.
18 # The most recent version and complete docs are available at:
19 # http://stein.cshl.org/WWW/software/CGI/
21 $CGI::revision = '$Id: CGI.pm,v 1.49 2001/02/04 23:08:39 lstein Exp $';
22 $CGI::VERSION='2.753';
24 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
25 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
26 # $TempFile::TMPDIRECTORY = '/usr/tmp';
27 use CGI::Util qw(rearrange make_attributes unescape escape expires);
29 use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
32 # >>>>> Here are some globals that you might want to adjust <<<<<<
33 sub initialize_globals {
34 # Set this to 1 to enable copious autoloader debugging messages
37 # Set this to 1 to generate XTML-compatible output
40 # Change this to the preferred DTD to print in start_html()
41 # or use default_dtd('text of DTD to use');
42 $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
43 'http://www.w3.org/TR/html4/loose.dtd' ] ;
45 # Set this to 1 to enable NOSTICKY scripts
47 # 1) use CGI qw(-nosticky)
48 # 2) $CGI::nosticky(1)
51 # Set this to 1 to enable NPH scripts
55 # 3) print header(-nph=>1)
58 # Set this to 1 to enable debugging from @ARGV
59 # Set to 2 to enable debugging from STDIN
62 # Set this to 1 to make the temporary files created
63 # during file uploads safe from prying eyes
65 # 1) use CGI qw(:private_tempfiles)
66 # 2) CGI::private_tempfiles(1);
67 $PRIVATE_TEMPFILES = 0;
69 # Set this to a positive value to limit the size of a POSTing
70 # to a certain number of bytes:
73 # Change this to 1 to disable uploads entirely:
76 # Automatically determined -- don't change
79 # Change this to 1 to suppress redundant HTTP headers
82 # separate the name=value pairs by semicolons rather than ampersands
83 $USE_PARAM_SEMICOLONS = 1;
85 # Do not include undefined params parsed from query string
86 # use CGI qw(-no_undef_params);
89 # Other globals that you shouldn't worry about.
95 undef %QUERY_FIELDNAMES;
97 # prevent complaints by mod_perl
101 # ------------------ START OF THE LIBRARY ------------
104 initialize_globals();
106 # FIGURE OUT THE OS WE'RE RUNNING UNDER
107 # Some systems support the $^O variable. If not
108 # available then require() the Config library
112 $OS = $Config::Config{'osname'};
115 if ($OS =~ /^MSWin/i) {
117 } elsif ($OS =~ /^VMS/i) {
119 } elsif ($OS =~ /^dos/i) {
121 } elsif ($OS =~ /^MacOS/i) {
123 } elsif ($OS =~ /^os2/i) {
125 } elsif ($OS =~ /^epoc/i) {
131 # Some OS logic. Binary mode enabled on DOS, NT and VMS
132 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin)/;
134 # This is the default class for the CGI object to use when all else fails.
135 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
137 # This is where to look for autoloaded routines.
138 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
140 # The path separator is a slash, backslash or semicolon, depending
143 UNIX=>'/', OS2=>'\\', EPOC=>'/',
144 WINDOWS=>'\\', DOS=>'\\', MACINTOSH=>':', VMS=>'/'
147 # This no longer seems to be necessary
148 # Turn on NPH scripts by default when running under IIS server!
149 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
150 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
152 # Turn on special checking for Doug MacEachern's modperl
153 if (exists $ENV{'GATEWAY_INTERFACE'}
155 ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//))
160 # Turn on special checking for ActiveState's PerlEx
161 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
163 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
164 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
165 # and sometimes CR). The most popular VMS web server
166 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
167 # use ASCII, so \015\012 means something different. I find this all
169 $EBCDIC = "\t" ne "\011";
178 if ($needs_binmode) {
179 $CGI::DefaultClass->binmode(main::STDOUT);
180 $CGI::DefaultClass->binmode(main::STDIN);
181 $CGI::DefaultClass->binmode(main::STDERR);
185 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
186 tt u i b blockquote pre img a address cite samp dfn html head
187 base body Link nextid title meta kbd start_html end_html
188 input Select option comment charset escapeHTML/],
189 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
190 embed basefont style span layer ilayer font frameset frame script small big/],
191 ':netscape'=>[qw/blink fontsize center/],
192 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
193 submit reset defaults radio_group popup_menu button autoEscape
194 scrolling_list image_button start_form end_form startform endform
195 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
196 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
197 raw_cookie request_method query_string Accept user_agent remote_host content_type
198 remote_addr referer server_name server_software server_port server_protocol
199 virtual_host remote_ident auth_type http
200 save_parameters restore_parameters param_fetch
201 remote_user user_name header redirect import_names put
202 Delete Delete_all url_param cgi_error/],
203 ':ssl' => [qw/https/],
204 ':imagemap' => [qw/Area Map/],
205 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
206 ':html' => [qw/:html2 :html3 :netscape/],
207 ':standard' => [qw/:html2 :html3 :form :cgi/],
208 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
209 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal/]
212 # to import symbols into caller
216 # This causes modules to clash.
220 $self->_setup_symbols(@_);
221 my ($callpack, $callfile, $callline) = caller;
223 # To allow overriding, search through the packages
224 # Till we find one in which the correct subroutine is defined.
225 my @packages = ($self,@{"$self\:\:ISA"});
226 foreach $sym (keys %EXPORT) {
228 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
229 foreach $pck (@packages) {
230 if (defined(&{"$pck\:\:$sym"})) {
235 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
241 $pack->_setup_symbols('-compile',@_);
246 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
248 return ($tag) unless $EXPORT_TAGS{$tag};
249 foreach (@{$EXPORT_TAGS{$tag}}) {
250 push(@r,&expand_tags($_));
256 # The new routine. This will check the current environment
257 # for an existing query string, and initialize itself, if so.
260 my($class,$initializer) = @_;
262 bless $self,ref $class || $class || $DefaultClass;
263 if ($MOD_PERL && defined Apache->request) {
264 Apache->request->register_cleanup(\&CGI::_reset_globals);
267 $self->_reset_globals if $PERLEX;
268 $self->init($initializer);
272 # We provide a DESTROY method so that the autoloader
273 # doesn't bother trying to find it.
277 # Returns the value(s)of a named parameter.
278 # If invoked in a list context, returns the
279 # entire list. Otherwise returns the first
280 # member of the list.
281 # If name is not provided, return a list of all
282 # the known parameters names available.
283 # If more than one argument is provided, the
284 # second and subsequent arguments are used to
285 # set the value of the parameter.
288 my($self,@p) = self_or_default(@_);
289 return $self->all_parameters unless @p;
290 my($name,$value,@other);
292 # For compatibility between old calling style and use_named_parameters() style,
293 # we have to special case for a single parameter present.
295 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
298 if (substr($p[0],0,1) eq '-') {
299 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
301 foreach ($value,@other) {
302 push(@values,$_) if defined($_);
305 # If values is provided, then we set it.
307 $self->add_parameter($name);
308 $self->{$name}=[@values];
314 return unless defined($name) && $self->{$name};
315 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
318 sub self_or_default {
319 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
320 unless (defined($_[0]) &&
321 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
323 $Q = $CGI::DefaultClass->new unless defined($Q);
326 return wantarray ? @_ : $Q;
330 local $^W=0; # prevent a warning
331 if (defined($_[0]) &&
332 (substr(ref($_[0]),0,3) eq 'CGI'
333 || UNIVERSAL::isa($_[0],'CGI'))) {
336 return ($DefaultClass,@_);
340 ########################################
341 # THESE METHODS ARE MORE OR LESS PRIVATE
342 # GO TO THE __DATA__ SECTION TO SEE MORE
344 ########################################
346 # Initialize the query object from the environment.
347 # If a parameter list is found, this object will be set
348 # to an associative array in which parameter names are keys
349 # and the values are stored as lists
350 # If a keyword list is found, this method creates a bogus
351 # parameter list with the single parameter 'keywords'.
354 my($self,$initializer) = @_;
355 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
358 # if we get called more than once, we want to initialize
359 # ourselves from the original query (which may be gone
360 # if it was read from STDIN originally.)
361 if (defined(@QUERY_PARAM) && !defined($initializer)) {
362 foreach (@QUERY_PARAM) {
363 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
365 $self->charset($QUERY_CHARSET);
366 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
370 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
371 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
373 $fh = to_filehandle($initializer) if $initializer;
375 # set charset to the safe ISO-8859-1
376 $self->charset('ISO-8859-1');
380 # avoid unreasonably large postings
381 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
382 $self->cgi_error("413 Request entity too large");
386 # Process multipart postings, but only if the initializer is
389 && defined($ENV{'CONTENT_TYPE'})
390 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
391 && !defined($initializer)
393 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
394 $self->read_multipart($boundary,$content_length);
398 # If initializer is defined, then read parameters
400 if (defined($initializer)) {
401 if (UNIVERSAL::isa($initializer,'CGI')) {
402 $query_string = $initializer->query_string;
405 if (ref($initializer) && ref($initializer) eq 'HASH') {
406 foreach (keys %$initializer) {
407 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
412 if (defined($fh) && ($fh ne '')) {
418 # massage back into standard format
419 if ("@lines" =~ /=/) {
420 $query_string=join("&",@lines);
422 $query_string=join("+",@lines);
427 # last chance -- treat it as a string
428 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
429 $query_string = $initializer;
434 # If method is GET or HEAD, fetch the query from
436 if ($meth=~/^(GET|HEAD)$/) {
438 $query_string = Apache->request->args;
440 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
441 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
446 if ($meth eq 'POST') {
447 $self->read_from_client(\*STDIN,\$query_string,$content_length,0)
448 if $content_length > 0;
449 # Some people want to have their cake and eat it too!
450 # Uncomment this line to have the contents of the query string
451 # APPENDED to the POST data.
452 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
456 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
457 # Check the command line and then the standard input for data.
458 # We use the shellwords package in order to behave the way that
459 # UN*X programmers expect.
460 $query_string = read_from_cmdline() if $DEBUG;
463 # We now have the query string in hand. We do slightly
464 # different things for keyword lists and parameter lists.
465 if (defined $query_string && length $query_string) {
466 if ($query_string =~ /[&=;]/) {
467 $self->parse_params($query_string);
469 $self->add_parameter('keywords');
470 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
474 # Special case. Erase everything if there is a field named
476 if ($self->param('.defaults')) {
480 # Associative array containing our defined fieldnames
481 $self->{'.fieldnames'} = {};
482 foreach ($self->param('.cgifields')) {
483 $self->{'.fieldnames'}->{$_}++;
486 # Clear out our default submission button flag if present
487 $self->delete('.submit');
488 $self->delete('.cgifields');
490 $self->save_request unless $initializer;
493 # FUNCTIONS TO OVERRIDE:
494 # Turn a string into a filehandle
497 return undef unless $thingy;
498 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
499 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
502 while (my $package = caller($caller++)) {
503 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
504 return $tmp if defined(fileno($tmp));
510 # send output to the browser
512 my($self,@p) = self_or_default(@_);
516 # print to standard output (for overriding in mod_perl)
522 # get/set last cgi_error
524 my ($self,$err) = self_or_default(@_);
525 $self->{'.cgi_error'} = $err if defined $err;
526 return $self->{'.cgi_error'};
531 # We're going to play with the package globals now so that if we get called
532 # again, we initialize ourselves in exactly the same way. This allows
533 # us to have several of these objects.
534 @QUERY_PARAM = $self->param; # save list of parameters
535 foreach (@QUERY_PARAM) {
536 next unless defined $_;
537 $QUERY_PARAM{$_}=$self->{$_};
539 $QUERY_CHARSET = $self->charset;
540 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
544 my($self,$tosplit) = @_;
545 my(@pairs) = split(/[&;]/,$tosplit);
548 ($param,$value) = split('=',$_,2);
549 next if $NO_UNDEF_PARAMS and not $value;
550 $value = '' unless defined $value;
551 $param = unescape($param);
552 $value = unescape($value);
553 $self->add_parameter($param);
554 push (@{$self->{$param}},$value);
560 return unless defined $param;
561 push (@{$self->{'.parameters'}},$param)
562 unless defined($self->{$param});
567 return () unless defined($self) && $self->{'.parameters'};
568 return () unless @{$self->{'.parameters'}};
569 return @{$self->{'.parameters'}};
572 # put a filehandle into binary mode (DOS)
574 CORE::binmode($_[1]);
578 my ($self,$tagname) = @_;
583 (substr(ref(\$_[0]),0,3) eq 'CGI' ||
584 UNIVERSAL::isa(\$_[0],'CGI')));
586 if (ref(\$_[0]) && ref(\$_[0]) eq 'HASH') {
587 my(\@attr) = make_attributes(shift()||undef,1);
588 \$attr = " \@attr" if \@attr;
591 if ($tagname=~/start_(\w+)/i) {
592 $func .= qq! return "<\L$1\E\$attr>";} !;
593 } elsif ($tagname=~/end_(\w+)/i) {
594 $func .= qq! return "<\L/$1\E>"; } !;
597 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@_;
598 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
599 my \@result = map { "\$tag\$_\$untag" }
600 (ref(\$_[0]) eq 'ARRAY') ? \@{\$_[0]} : "\@_";
608 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
609 my $func = &_compile;
614 my($func) = $AUTOLOAD;
615 my($pack,$func_name);
617 local($1,$2); # this fixes an obscure variable suicide problem.
618 $func=~/(.+)::([^:]+)$/;
619 ($pack,$func_name) = ($1,$2);
620 $pack=~s/::SUPER$//; # fix another obscure problem
621 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
622 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
624 my($sub) = \%{"$pack\:\:SUBS"};
626 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
627 eval "package $pack; $$auto";
628 croak("$AUTOLOAD: $@") if $@;
629 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
631 my($code) = $sub->{$func_name};
633 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
635 (my $base = $func_name) =~ s/^(start_|end_)//i;
636 if ($EXPORT{':any'} ||
639 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
640 && $EXPORT_OK{$base}) {
641 $code = $CGI::DefaultClass->_make_tag_func($func_name);
644 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
645 eval "package $pack; $code";
648 croak("$AUTOLOAD: $@");
651 CORE::delete($sub->{$func_name}); #free storage
652 return "$pack\:\:$func_name";
655 sub _reset_globals { initialize_globals(); }
661 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
662 $NPH++, next if /^[:-]nph$/;
663 $NOSTICKY++, next if /^[:-]nosticky$/;
664 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
665 $DEBUG=2, next if /^[:-][Dd]ebug$/;
666 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
667 $XHTML++, next if /^[:-]xhtml$/;
668 $XHTML=0, next if /^[:-]no_?xhtml$/;
669 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
670 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
671 $EXPORT{$_}++, next if /^[:-]any$/;
672 $compile++, next if /^[:-]compile$/;
673 $NO_UNDEF_PARAMS++, next if /^[:-]no_undef_params$/;
675 # This is probably extremely evil code -- to be deleted some day.
676 if (/^[-]autoload$/) {
677 my($pkg) = caller(1);
678 *{"${pkg}::AUTOLOAD"} = sub {
679 my($routine) = $AUTOLOAD;
680 $routine =~ s/^.*::/CGI::/;
686 foreach (&expand_tags($_)) {
687 tr/a-zA-Z0-9_//cd; # don't allow weird function names
691 _compile_all(keys %EXPORT) if $compile;
695 my ($self,$charset) = self_or_default(@_);
696 $self->{'.charset'} = $charset if defined $charset;
700 ###############################################################################
701 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
702 ###############################################################################
703 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
704 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
708 'URL_ENCODED'=> <<'END_OF_FUNC',
709 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
712 'MULTIPART' => <<'END_OF_FUNC',
713 sub MULTIPART { 'multipart/form-data'; }
716 'SERVER_PUSH' => <<'END_OF_FUNC',
717 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
720 'new_MultipartBuffer' => <<'END_OF_FUNC',
721 # Create a new multipart buffer
722 sub new_MultipartBuffer {
723 my($self,$boundary,$length,$filehandle) = @_;
724 return MultipartBuffer->new($self,$boundary,$length,$filehandle);
728 'read_from_client' => <<'END_OF_FUNC',
729 # Read data from a file handle
730 sub read_from_client {
731 my($self, $fh, $buff, $len, $offset) = @_;
732 local $^W=0; # prevent a warning
733 return undef unless defined($fh);
734 return read($fh, $$buff, $len, $offset);
738 'delete' => <<'END_OF_FUNC',
740 # Deletes the named parameter entirely.
743 my($self,@p) = self_or_default(@_);
744 my($name) = rearrange([NAME],@p);
745 CORE::delete $self->{$name};
746 CORE::delete $self->{'.fieldnames'}->{$name};
747 @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
748 return wantarray ? () : undef;
752 #### Method: import_names
753 # Import all parameters into the given namespace.
754 # Assumes namespace 'Q' if not specified
756 'import_names' => <<'END_OF_FUNC',
758 my($self,$namespace,$delete) = self_or_default(@_);
759 $namespace = 'Q' unless defined($namespace);
760 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
761 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
762 # can anyone find an easier way to do this?
763 foreach (keys %{"${namespace}::"}) {
764 local *symbol = "${namespace}::${_}";
770 my($param,@value,$var);
771 foreach $param ($self->param) {
772 # protect against silly names
773 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
774 $var =~ s/^(?=\d)/_/;
775 local *symbol = "${namespace}::$var";
776 @value = $self->param($param);
783 #### Method: keywords
784 # Keywords acts a bit differently. Calling it in a list context
785 # returns the list of keywords.
786 # Calling it in a scalar context gives you the size of the list.
788 'keywords' => <<'END_OF_FUNC',
790 my($self,@values) = self_or_default(@_);
791 # If values is provided, then we set it.
792 $self->{'keywords'}=[@values] if @values;
793 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
798 # These are some tie() interfaces for compatibility
799 # with Steve Brenner's cgi-lib.pl routines
800 'Vars' => <<'END_OF_FUNC',
805 return %in if wantarray;
810 # These are some tie() interfaces for compatibility
811 # with Steve Brenner's cgi-lib.pl routines
812 'ReadParse' => <<'END_OF_FUNC',
822 return scalar(keys %in);
826 'PrintHeader' => <<'END_OF_FUNC',
828 my($self) = self_or_default(@_);
829 return $self->header();
833 'HtmlTop' => <<'END_OF_FUNC',
835 my($self,@p) = self_or_default(@_);
836 return $self->start_html(@p);
840 'HtmlBot' => <<'END_OF_FUNC',
842 my($self,@p) = self_or_default(@_);
843 return $self->end_html(@p);
847 'SplitParam' => <<'END_OF_FUNC',
850 my (@params) = split ("\0", $param);
851 return (wantarray ? @params : $params[0]);
855 'MethGet' => <<'END_OF_FUNC',
857 return request_method() eq 'GET';
861 'MethPost' => <<'END_OF_FUNC',
863 return request_method() eq 'POST';
867 'TIEHASH' => <<'END_OF_FUNC',
869 return $_[1] if defined $_[1];
870 return $Q ||= new shift;
874 'STORE' => <<'END_OF_FUNC',
879 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
880 $self->param(-name=>$tag,-value=>\@vals);
884 'FETCH' => <<'END_OF_FUNC',
886 return $_[0] if $_[1] eq 'CGI';
887 return undef unless defined $_[0]->param($_[1]);
888 return join("\0",$_[0]->param($_[1]));
892 'FIRSTKEY' => <<'END_OF_FUNC',
894 $_[0]->{'.iterator'}=0;
895 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
899 'NEXTKEY' => <<'END_OF_FUNC',
901 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
905 'EXISTS' => <<'END_OF_FUNC',
907 exists $_[0]->{$_[1]};
911 'DELETE' => <<'END_OF_FUNC',
913 $_[0]->delete($_[1]);
917 'CLEAR' => <<'END_OF_FUNC',
925 # Append a new value to an existing query
930 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
931 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
933 $self->add_parameter($name);
934 push(@{$self->{$name}},@values);
936 return $self->param($name);
940 #### Method: delete_all
941 # Delete all parameters
943 'delete_all' => <<'EOF',
945 my($self) = self_or_default(@_);
952 my($self,@p) = self_or_default(@_);
957 'Delete_all' => <<'EOF',
959 my($self,@p) = self_or_default(@_);
960 $self->delete_all(@p);
964 #### Method: autoescape
965 # If you want to turn off the autoescaping features,
966 # call this method with undef as the argument
967 'autoEscape' => <<'END_OF_FUNC',
969 my($self,$escape) = self_or_default(@_);
970 $self->{'dontescape'}=!$escape;
976 # Return the current version
978 'version' => <<'END_OF_FUNC',
984 #### Method: url_param
985 # Return a parameter in the QUERY_STRING, regardless of
986 # whether this was a POST or a GET
988 'url_param' => <<'END_OF_FUNC',
990 my ($self,@p) = self_or_default(@_);
991 my $name = shift(@p);
992 return undef unless exists($ENV{QUERY_STRING});
993 unless (exists($self->{'.url_param'})) {
994 $self->{'.url_param'}={}; # empty hash
995 if ($ENV{QUERY_STRING} =~ /=/) {
996 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
999 ($param,$value) = split('=',$_,2);
1000 $param = unescape($param);
1001 $value = unescape($value);
1002 push(@{$self->{'.url_param'}->{$param}},$value);
1005 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1008 return keys %{$self->{'.url_param'}} unless defined($name);
1009 return () unless $self->{'.url_param'}->{$name};
1010 return wantarray ? @{$self->{'.url_param'}->{$name}}
1011 : $self->{'.url_param'}->{$name}->[0];
1016 # Returns a string in which all the known parameter/value
1017 # pairs are represented as nested lists, mainly for the purposes
1020 'Dump' => <<'END_OF_FUNC',
1022 my($self) = self_or_default(@_);
1023 my($param,$value,@result);
1024 return '<UL></UL>' unless $self->param;
1025 push(@result,"<UL>");
1026 foreach $param ($self->param) {
1027 my($name)=$self->escapeHTML($param);
1028 push(@result,"<LI><STRONG>$param</STRONG>");
1029 push(@result,"<UL>");
1030 foreach $value ($self->param($param)) {
1031 $value = $self->escapeHTML($value);
1032 $value =~ s/\n/<BR>\n/g;
1033 push(@result,"<LI>$value");
1035 push(@result,"</UL>");
1037 push(@result,"</UL>\n");
1038 return join("\n",@result);
1042 #### Method as_string
1044 # synonym for "dump"
1046 'as_string' => <<'END_OF_FUNC',
1053 # Write values out to a filehandle in such a way that they can
1054 # be reinitialized by the filehandle form of the new() method
1056 'save' => <<'END_OF_FUNC',
1058 my($self,$filehandle) = self_or_default(@_);
1059 $filehandle = to_filehandle($filehandle);
1061 local($,) = ''; # set print field separator back to a sane value
1062 local($\) = ''; # set output line separator to a sane value
1063 foreach $param ($self->param) {
1064 my($escaped_param) = escape($param);
1066 foreach $value ($self->param($param)) {
1067 print $filehandle "$escaped_param=",escape("$value"),"\n";
1070 foreach (keys %{$self->{'.fieldnames'}}) {
1071 print $filehandle ".cgifields=",escape("$_"),"\n";
1073 print $filehandle "=\n"; # end of record
1078 #### Method: save_parameters
1079 # An alias for save() that is a better name for exportation.
1080 # Only intended to be used with the function (non-OO) interface.
1082 'save_parameters' => <<'END_OF_FUNC',
1083 sub save_parameters {
1085 return save(to_filehandle($fh));
1089 #### Method: restore_parameters
1090 # A way to restore CGI parameters from an initializer.
1091 # Only intended to be used with the function (non-OO) interface.
1093 'restore_parameters' => <<'END_OF_FUNC',
1094 sub restore_parameters {
1095 $Q = $CGI::DefaultClass->new(@_);
1099 #### Method: multipart_init
1100 # Return a Content-Type: style header for server-push
1101 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1103 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1104 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1106 'multipart_init' => <<'END_OF_FUNC',
1107 sub multipart_init {
1108 my($self,@p) = self_or_default(@_);
1109 my($boundary,@other) = rearrange([BOUNDARY],@p);
1110 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1111 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1112 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1113 $type = SERVER_PUSH($boundary);
1114 return $self->header(
1117 (map { split "=", $_, 2 } @other),
1118 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1123 #### Method: multipart_start
1124 # Return a Content-Type: style header for server-push, start of section
1126 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1127 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1129 'multipart_start' => <<'END_OF_FUNC',
1130 sub multipart_start {
1132 my($self,@p) = self_or_default(@_);
1133 my($type,@other) = rearrange([TYPE],@p);
1134 $type = $type || 'text/html';
1135 push(@header,"Content-Type: $type");
1137 # rearrange() was designed for the HTML portion, so we
1138 # need to fix it up a little.
1140 next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1141 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1143 push(@header,@other);
1144 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1150 #### Method: multipart_end
1151 # Return a MIME boundary separator for server-push, end of section
1153 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1156 'multipart_end' => <<'END_OF_FUNC',
1158 my($self,@p) = self_or_default(@_);
1159 return $self->{'separator'};
1164 #### Method: multipart_final
1165 # Return a MIME boundary separator for server-push, end of all sections
1167 # Contributed by Andrew Benham (adsb@bigfoot.com)
1169 'multipart_final' => <<'END_OF_FUNC',
1170 sub multipart_final {
1171 my($self,@p) = self_or_default(@_);
1172 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1178 # Return a Content-Type: style header
1181 'header' => <<'END_OF_FUNC',
1183 my($self,@p) = self_or_default(@_);
1186 return undef if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1188 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,@other) =
1189 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1190 'STATUS',['COOKIE','COOKIES'],'TARGET',
1191 'EXPIRES','NPH','CHARSET',
1195 if (defined $charset) {
1196 $self->charset($charset);
1198 $charset = $self->charset;
1201 # rearrange() was designed for the HTML portion, so we
1202 # need to fix it up a little.
1204 next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1205 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1208 $type ||= 'text/html' unless defined($type);
1209 $type .= "; charset=$charset" if $type ne '' and $type =~ m!^text/! and $type !~ /\bcharset\b/;
1211 # Maybe future compatibility. Maybe not.
1212 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1213 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1214 push(@header,"Server: " . &server_software()) if $nph;
1216 push(@header,"Status: $status") if $status;
1217 push(@header,"Window-Target: $target") if $target;
1218 # push all the cookies -- there may be several
1220 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1222 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1223 push(@header,"Set-Cookie: $cs") if $cs ne '';
1226 # if the user indicates an expiration time, then we need
1227 # both an Expires and a Date header (so that the browser is
1229 push(@header,"Expires: " . expires($expires,'http'))
1231 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1232 push(@header,"Pragma: no-cache") if $self->cache();
1233 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1234 push(@header,@other);
1235 push(@header,"Content-Type: $type") if $type ne '';
1237 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1238 if ($MOD_PERL and not $nph) {
1239 my $r = Apache->request;
1240 $r->send_cgi_header($header);
1249 # Control whether header() will produce the no-cache
1252 'cache' => <<'END_OF_FUNC',
1254 my($self,$new_value) = self_or_default(@_);
1255 $new_value = '' unless $new_value;
1256 if ($new_value ne '') {
1257 $self->{'cache'} = $new_value;
1259 return $self->{'cache'};
1264 #### Method: redirect
1265 # Return a Location: style header
1268 'redirect' => <<'END_OF_FUNC',
1270 my($self,@p) = self_or_default(@_);
1271 my($url,$target,$cookie,$nph,@other) = rearrange([[LOCATION,URI,URL],TARGET,COOKIE,NPH],@p);
1272 $url ||= $self->self_url;
1274 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1276 '-Status'=>'302 Moved',
1279 unshift(@o,'-Target'=>$target) if $target;
1280 unshift(@o,'-Cookie'=>$cookie) if $cookie;
1281 unshift(@o,'-Type'=>'');
1282 return $self->header(@o);
1287 #### Method: start_html
1288 # Canned HTML header
1291 # $title -> (optional) The title for this HTML document (-title)
1292 # $author -> (optional) e-mail address of the author (-author)
1293 # $base -> (optional) if set to true, will enter the BASE address of this document
1294 # for resolving relative references (-base)
1295 # $xbase -> (optional) alternative base at some remote location (-xbase)
1296 # $target -> (optional) target window to load all links into (-target)
1297 # $script -> (option) Javascript code (-script)
1298 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1299 # $meta -> (optional) Meta information tags
1300 # $head -> (optional) any other elements you'd like to incorporate into the <HEAD> tag
1301 # (a scalar or array ref)
1302 # $style -> (optional) reference to an external style sheet
1303 # @other -> (optional) any other named parameters you'd like to incorporate into
1306 'start_html' => <<'END_OF_FUNC',
1308 my($self,@p) = &self_or_default(@_);
1309 my($title,$author,$base,$xbase,$script,$noscript,$target,$meta,$head,$style,$dtd,$lang,@other) =
1310 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD,LANG],@p);
1312 # strangely enough, the title needs to be escaped as HTML
1313 # while the author needs to be escaped as a URL
1314 $title = $self->escapeHTML($title || 'Untitled Document');
1315 $author = $self->escape($author);
1317 my(@result,$xml_dtd);
1319 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1320 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1322 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1325 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1328 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1329 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1330 push @result,q(<?xml version="1.0" encoding="utf-8"?>) if $xml_dtd;
1332 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1333 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t"$dtd->[1]">));
1335 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1337 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang"><head><title>$title</title>)
1338 : qq(<html lang="$lang"><head><title>$title</title>));
1339 if (defined $author) {
1340 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1341 : "<link rev=\"made\" href=\"mailto:$author\">");
1344 if ($base || $xbase || $target) {
1345 my $href = $xbase || $self->url('-path'=>1);
1346 my $t = $target ? qq/ target="$target"/ : '';
1347 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1350 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1351 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1352 : qq(<meta name="$_" content="$meta->{$_}">)); }
1355 push(@result,ref($head) ? @$head : $head) if $head;
1357 # handle the infrequently-used -style and -script parameters
1358 push(@result,$self->_style($style)) if defined $style;
1359 push(@result,$self->_script($script)) if defined $script;
1361 # handle -noscript parameter
1362 push(@result,<<END) if $noscript;
1368 my($other) = @other ? " @other" : '';
1369 push(@result,"</head><body$other>");
1370 return join("\n",@result);
1375 # internal method for generating a CSS style section
1377 '_style' => <<'END_OF_FUNC',
1379 my ($self,$style) = @_;
1381 my $type = 'text/css';
1383 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1384 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1387 my($src,$code,$stype,@other) =
1388 rearrange([SRC,CODE,TYPE],
1389 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1390 ref($style) eq 'ARRAY' ? @$style : %$style);
1391 $type = $stype if $stype;
1392 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1393 { # If it is, push a LINK tag for each one.
1394 foreach $src (@$src)
1396 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1397 : qq(<link rel="stylesheet" type="$type" href="$src">/)) if $src;
1401 { # Otherwise, push the single -src, if it exists.
1402 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1403 : qq(<link rel="stylesheet" type="$type" href="$src">)
1406 push(@result,style({'type'=>$type},"$cdata_start\n$code\n$cdata_end")) if $code;
1408 push(@result,style({'type'=>$type},"$cdata_start\n$style\n$cdata_end"));
1414 '_script' => <<'END_OF_FUNC',
1416 my ($self,$script) = @_;
1419 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1420 foreach $script (@scripts) {
1421 my($src,$code,$language);
1422 if (ref($script)) { # script is a hash
1423 ($src,$code,$language, $type) =
1424 rearrange([SRC,CODE,LANGUAGE,TYPE],
1425 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1426 ref($script) eq 'ARRAY' ? @$script : %$script);
1427 # User may not have specified language
1428 $language ||= 'JavaScript';
1429 unless (defined $type) {
1430 $type = lc $language;
1431 # strip '1.2' from 'javascript1.2'
1432 $type =~ s/^(\D+).*$/text\/$1/;
1435 ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
1438 my $comment = '//'; # javascript by default
1439 $comment = '#' if $type=~/perl|tcl/i;
1440 $comment = "'" if $type=~/vbscript/i;
1442 my $cdata_start = "\n<!-- Hide script\n";
1443 $cdata_start .= "$comment<![CDATA[\n" if $XHTML;
1444 my $cdata_end = $XHTML ? "\n$comment]]>" : $comment;
1445 $cdata_end .= " End script hiding -->\n";
1448 push(@satts,'src'=>$src) if $src;
1449 push(@satts,'language'=>$language);
1450 push(@satts,'type'=>$type);
1451 $code = "$cdata_start$code$cdata_end" if defined $code;
1452 push(@result,script({@satts},$code || ''));
1458 #### Method: end_html
1459 # End an HTML document.
1460 # Trivial method for completeness. Just returns "</BODY>"
1462 'end_html' => <<'END_OF_FUNC',
1464 return "</body></html>";
1469 ################################
1470 # METHODS USED IN BUILDING FORMS
1471 ################################
1473 #### Method: isindex
1474 # Just prints out the isindex tag.
1476 # $action -> optional URL of script to run
1478 # A string containing a <ISINDEX> tag
1479 'isindex' => <<'END_OF_FUNC',
1481 my($self,@p) = self_or_default(@_);
1482 my($action,@other) = rearrange([ACTION],@p);
1483 $action = qq/action="$action"/ if $action;
1484 my($other) = @other ? " @other" : '';
1485 return $XHTML ? "<isindex $action$other />" : "<isindex $action$other>";
1490 #### Method: startform
1493 # $method -> optional submission method to use (GET or POST)
1494 # $action -> optional URL of script to run
1495 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1496 'startform' => <<'END_OF_FUNC',
1498 my($self,@p) = self_or_default(@_);
1500 my($method,$action,$enctype,@other) =
1501 rearrange([METHOD,ACTION,ENCTYPE],@p);
1503 $method = lc($method) || 'post';
1504 $enctype = $enctype || &URL_ENCODED;
1505 unless (defined $action) {
1506 $action = $self->url(-absolute=>1,-path=>1);
1507 $action .= "?$ENV{QUERY_STRING}" if $ENV{QUERY_STRING};
1509 $action = qq(action="$action");
1510 my($other) = @other ? " @other" : '';
1511 $self->{'.parametersToAdd'}={};
1512 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1517 #### Method: start_form
1518 # synonym for startform
1519 'start_form' => <<'END_OF_FUNC',
1525 'end_multipart_form' => <<'END_OF_FUNC',
1526 sub end_multipart_form {
1531 #### Method: start_multipart_form
1532 # synonym for startform
1533 'start_multipart_form' => <<'END_OF_FUNC',
1534 sub start_multipart_form {
1535 my($self,@p) = self_or_default(@_);
1536 if (defined($param[0]) && substr($param[0],0,1) eq '-') {
1538 $p{'-enctype'}=&MULTIPART;
1539 return $self->startform(%p);
1541 my($method,$action,@other) =
1542 rearrange([METHOD,ACTION],@p);
1543 return $self->startform($method,$action,&MULTIPART,@other);
1549 #### Method: endform
1551 'endform' => <<'END_OF_FUNC',
1553 my($self,@p) = self_or_default(@_);
1555 return wantarray ? ("</form>") : "\n</form>";
1557 return wantarray ? ($self->get_fields,"</form>") :
1558 $self->get_fields ."\n</form>";
1564 #### Method: end_form
1565 # synonym for endform
1566 'end_form' => <<'END_OF_FUNC',
1573 '_textfield' => <<'END_OF_FUNC',
1575 my($self,$tag,@p) = self_or_default(@_);
1576 my($name,$default,$size,$maxlength,$override,@other) =
1577 rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1579 my $current = $override ? $default :
1580 (defined($self->param($name)) ? $self->param($name) : $default);
1582 $current = defined($current) ? $self->escapeHTML($current,1) : '';
1583 $name = defined($name) ? $self->escapeHTML($name) : '';
1584 my($s) = defined($size) ? qq/ size="$size"/ : '';
1585 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1586 my($other) = @other ? " @other" : '';
1587 # this entered at cristy's request to fix problems with file upload fields
1588 # and WebTV -- not sure it won't break stuff
1589 my($value) = $current ne '' ? qq(value="$current") : '';
1590 return $XHTML ? qq(<input type="$tag" name="$name" $value$s$m$other />)
1591 : qq/<input type="$tag" name="$name" $value$s$m$other>/;
1595 #### Method: textfield
1597 # $name -> Name of the text field
1598 # $default -> Optional default value of the field if not
1600 # $size -> Optional width of field in characaters.
1601 # $maxlength -> Optional maximum number of characters.
1603 # A string containing a <INPUT TYPE="text"> field
1605 'textfield' => <<'END_OF_FUNC',
1607 my($self,@p) = self_or_default(@_);
1608 $self->_textfield('text',@p);
1613 #### Method: filefield
1615 # $name -> Name of the file upload field
1616 # $size -> Optional width of field in characaters.
1617 # $maxlength -> Optional maximum number of characters.
1619 # A string containing a <INPUT TYPE="text"> field
1621 'filefield' => <<'END_OF_FUNC',
1623 my($self,@p) = self_or_default(@_);
1624 $self->_textfield('file',@p);
1629 #### Method: password
1630 # Create a "secret password" entry field
1632 # $name -> Name of the field
1633 # $default -> Optional default value of the field if not
1635 # $size -> Optional width of field in characters.
1636 # $maxlength -> Optional maximum characters that can be entered.
1638 # A string containing a <INPUT TYPE="password"> field
1640 'password_field' => <<'END_OF_FUNC',
1641 sub password_field {
1642 my ($self,@p) = self_or_default(@_);
1643 $self->_textfield('password',@p);
1647 #### Method: textarea
1649 # $name -> Name of the text field
1650 # $default -> Optional default value of the field if not
1652 # $rows -> Optional number of rows in text area
1653 # $columns -> Optional number of columns in text area
1655 # A string containing a <TEXTAREA></TEXTAREA> tag
1657 'textarea' => <<'END_OF_FUNC',
1659 my($self,@p) = self_or_default(@_);
1661 my($name,$default,$rows,$cols,$override,@other) =
1662 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1664 my($current)= $override ? $default :
1665 (defined($self->param($name)) ? $self->param($name) : $default);
1667 $name = defined($name) ? $self->escapeHTML($name) : '';
1668 $current = defined($current) ? $self->escapeHTML($current) : '';
1669 my($r) = $rows ? " rows=$rows" : '';
1670 my($c) = $cols ? " cols=$cols" : '';
1671 my($other) = @other ? " @other" : '';
1672 return qq{<textarea name="$name"$r$c$other>$current</textarea>};
1678 # Create a javascript button.
1680 # $name -> (optional) Name for the button. (-name)
1681 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1682 # $onclick -> (optional) Text of the JavaScript to run when the button is
1685 # A string containing a <INPUT TYPE="button"> tag
1687 'button' => <<'END_OF_FUNC',
1689 my($self,@p) = self_or_default(@_);
1691 my($label,$value,$script,@other) = rearrange([NAME,[VALUE,LABEL],
1692 [ONCLICK,SCRIPT]],@p);
1694 $label=$self->escapeHTML($label);
1695 $value=$self->escapeHTML($value,1);
1696 $script=$self->escapeHTML($script);
1699 $name = qq/ name="$label"/ if $label;
1700 $value = $value || $label;
1702 $val = qq/ value="$value"/ if $value;
1703 $script = qq/ onclick="$script"/ if $script;
1704 my($other) = @other ? " @other" : '';
1705 return $XHTML ? qq(<input type="button"$name$val$script$other />)
1706 : qq/<input type="button"$name$val$script$other>/;
1712 # Create a "submit query" button.
1714 # $name -> (optional) Name for the button.
1715 # $value -> (optional) Value of the button when selected (also doubles as label).
1716 # $label -> (optional) Label printed on the button(also doubles as the value).
1718 # A string containing a <INPUT TYPE="submit"> tag
1720 'submit' => <<'END_OF_FUNC',
1722 my($self,@p) = self_or_default(@_);
1724 my($label,$value,@other) = rearrange([NAME,[VALUE,LABEL]],@p);
1726 $label=$self->escapeHTML($label);
1727 $value=$self->escapeHTML($value,1);
1729 my($name) = ' name=".submit"' unless $NOSTICKY;
1730 $name = qq/ name="$label"/ if defined($label);
1731 $value = defined($value) ? $value : $label;
1733 $val = qq/ value="$value"/ if defined($value);
1734 my($other) = @other ? " @other" : '';
1735 return $XHTML ? qq(<input type="submit"$name$val$other />)
1736 : qq/<input type="submit"$name$val$other>/;
1742 # Create a "reset" button.
1744 # $name -> (optional) Name for the button.
1746 # A string containing a <INPUT TYPE="reset"> tag
1748 'reset' => <<'END_OF_FUNC',
1750 my($self,@p) = self_or_default(@_);
1751 my($label,@other) = rearrange([NAME],@p);
1752 $label=$self->escapeHTML($label);
1753 my($value) = defined($label) ? qq/ value="$label"/ : '';
1754 my($other) = @other ? " @other" : '';
1755 return $XHTML ? qq(<input type="reset"$value$other />)
1756 : qq/<input type="reset"$value$other>/;
1761 #### Method: defaults
1762 # Create a "defaults" button.
1764 # $name -> (optional) Name for the button.
1766 # A string containing a <INPUT TYPE="submit" NAME=".defaults"> tag
1768 # Note: this button has a special meaning to the initialization script,
1769 # and tells it to ERASE the current query string so that your defaults
1772 'defaults' => <<'END_OF_FUNC',
1774 my($self,@p) = self_or_default(@_);
1776 my($label,@other) = rearrange([[NAME,VALUE]],@p);
1778 $label=$self->escapeHTML($label,1);
1779 $label = $label || "Defaults";
1780 my($value) = qq/ value="$label"/;
1781 my($other) = @other ? " @other" : '';
1782 return $XHTML ? qq(<input type="submit" name=".defaults"$value$other />)
1783 : qq/<input type="submit" NAME=".defaults"$value$other>/;
1788 #### Method: comment
1789 # Create an HTML <!-- comment -->
1790 # Parameters: a string
1791 'comment' => <<'END_OF_FUNC',
1793 my($self,@p) = self_or_CGI(@_);
1794 return "<!-- @p -->";
1798 #### Method: checkbox
1799 # Create a checkbox that is not logically linked to any others.
1800 # The field value is "on" when the button is checked.
1802 # $name -> Name of the checkbox
1803 # $checked -> (optional) turned on by default if true
1804 # $value -> (optional) value of the checkbox, 'on' by default
1805 # $label -> (optional) a user-readable label printed next to the box.
1806 # Otherwise the checkbox name is used.
1808 # A string containing a <INPUT TYPE="checkbox"> field
1810 'checkbox' => <<'END_OF_FUNC',
1812 my($self,@p) = self_or_default(@_);
1814 my($name,$checked,$value,$label,$override,@other) =
1815 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1817 $value = defined $value ? $value : 'on';
1819 if (!$override && ($self->{'.fieldnames'}->{$name} ||
1820 defined $self->param($name))) {
1821 $checked = grep($_ eq $value,$self->param($name)) ? ' checked' : '';
1823 $checked = $checked ? qq/ checked/ : '';
1825 my($the_label) = defined $label ? $label : $name;
1826 $name = $self->escapeHTML($name);
1827 $value = $self->escapeHTML($value,1);
1828 $the_label = $self->escapeHTML($the_label);
1829 my($other) = @other ? " @other" : '';
1830 $self->register_parameter($name);
1831 return $XHTML ? qq{<input type="checkbox" name="$name" value="$value"$checked$other />$the_label}
1832 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
1837 #### Method: checkbox_group
1838 # Create a list of logically-linked checkboxes.
1840 # $name -> Common name for all the check boxes
1841 # $values -> A pointer to a regular array containing the
1842 # values for each checkbox in the group.
1843 # $defaults -> (optional)
1844 # 1. If a pointer to a regular array of checkbox values,
1845 # then this will be used to decide which
1846 # checkboxes to turn on by default.
1847 # 2. If a scalar, will be assumed to hold the
1848 # value of a single checkbox in the group to turn on.
1849 # $linebreak -> (optional) Set to true to place linebreaks
1850 # between the buttons.
1851 # $labels -> (optional)
1852 # A pointer to an associative array of labels to print next to each checkbox
1853 # in the form $label{'value'}="Long explanatory label".
1854 # Otherwise the provided values are used as the labels.
1856 # An ARRAY containing a series of <INPUT TYPE="checkbox"> fields
1858 'checkbox_group' => <<'END_OF_FUNC',
1859 sub checkbox_group {
1860 my($self,@p) = self_or_default(@_);
1862 my($name,$values,$defaults,$linebreak,$labels,$rows,$columns,
1863 $rowheaders,$colheaders,$override,$nolabels,@other) =
1864 rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1865 LINEBREAK,LABELS,ROWS,[COLUMNS,COLS],
1866 ROWHEADERS,COLHEADERS,
1867 [OVERRIDE,FORCE],NOLABELS],@p);
1869 my($checked,$break,$result,$label);
1871 my(%checked) = $self->previous_or_default($name,$defaults,$override);
1874 $break = $XHTML ? "<br />" : "<br>";
1879 $name=$self->escapeHTML($name);
1881 # Create the elements
1882 my(@elements,@values);
1884 @values = $self->_set_values_and_labels($values,\$labels,$name);
1886 my($other) = @other ? " @other" : '';
1888 $checked = $checked{$_} ? qq/ checked/ : '';
1890 unless (defined($nolabels) && $nolabels) {
1892 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1893 $label = $self->escapeHTML($label);
1895 $_ = $self->escapeHTML($_,1);
1896 push(@elements,$XHTML ? qq(<input type="checkbox" name="$name" value="$_"$checked$other />${label}${break})
1897 : qq/<input type="checkbox" name="$name" value="$_"$checked$other>${label}${break}/);
1899 $self->register_parameter($name);
1900 return wantarray ? @elements : join(' ',@elements)
1901 unless defined($columns) || defined($rows);
1902 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1906 # Escape HTML -- used internally
1907 'escapeHTML' => <<'END_OF_FUNC',
1909 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
1910 return undef unless defined($toencode);
1911 return $toencode if ref($self) && $self->{'dontescape'};
1912 $toencode =~ s{&}{&}gso;
1913 $toencode =~ s{<}{<}gso;
1914 $toencode =~ s{>}{>}gso;
1915 $toencode =~ s{"}{"}gso;
1916 my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
1917 uc $self->{'.charset'} eq 'WINDOWS-1252';
1918 if ($latin) { # bug in some browsers
1919 $toencode =~ s{'}{'}gso;
1920 $toencode =~ s{\x8b}{‹}gso;
1921 $toencode =~ s{\x9b}{›}gso;
1922 if (defined $newlinestoo && $newlinestoo) {
1923 $toencode =~ s{\012}{ }gso;
1924 $toencode =~ s{\015}{ }gso;
1931 # unescape HTML -- used internally
1932 'unescapeHTML' => <<'END_OF_FUNC',
1934 my ($self,$string) = CGI::self_or_default(@_);
1935 return undef unless defined($string);
1936 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
1938 # thanks to Randal Schwartz for the correct solution to this one
1939 $string=~ s[&(.*?);]{
1945 /^#(\d+)$/ && $latin ? chr($1) :
1946 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
1953 # Internal procedure - don't use
1954 '_tableize' => <<'END_OF_FUNC',
1956 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
1957 $rowheaders = [] unless defined $rowheaders;
1958 $colheaders = [] unless defined $colheaders;
1961 if (defined($columns)) {
1962 $rows = int(0.99 + @elements/$columns) unless defined($rows);
1964 if (defined($rows)) {
1965 $columns = int(0.99 + @elements/$rows) unless defined($columns);
1968 # rearrange into a pretty table
1969 $result = "<table>";
1971 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
1972 $result .= "<tr>" if @{$colheaders};
1973 foreach (@{$colheaders}) {
1974 $result .= "<th>$_</th>";
1976 for ($row=0;$row<$rows;$row++) {
1978 $result .= "<th>$rowheaders->[$row]</th>" if @$rowheaders;
1979 for ($column=0;$column<$columns;$column++) {
1980 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
1981 if defined($elements[$column*$rows + $row]);
1985 $result .= "</table>";
1991 #### Method: radio_group
1992 # Create a list of logically-linked radio buttons.
1994 # $name -> Common name for all the buttons.
1995 # $values -> A pointer to a regular array containing the
1996 # values for each button in the group.
1997 # $default -> (optional) Value of the button to turn on by default. Pass '-'
1998 # to turn _nothing_ on.
1999 # $linebreak -> (optional) Set to true to place linebreaks
2000 # between the buttons.
2001 # $labels -> (optional)
2002 # A pointer to an associative array of labels to print next to each checkbox
2003 # in the form $label{'value'}="Long explanatory label".
2004 # Otherwise the provided values are used as the labels.
2006 # An ARRAY containing a series of <INPUT TYPE="radio"> fields
2008 'radio_group' => <<'END_OF_FUNC',
2010 my($self,@p) = self_or_default(@_);
2012 my($name,$values,$default,$linebreak,$labels,
2013 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
2014 rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,
2015 ROWS,[COLUMNS,COLS],
2016 ROWHEADERS,COLHEADERS,
2017 [OVERRIDE,FORCE],NOLABELS],@p);
2018 my($result,$checked);
2020 if (!$override && defined($self->param($name))) {
2021 $checked = $self->param($name);
2023 $checked = $default;
2025 my(@elements,@values);
2026 @values = $self->_set_values_and_labels($values,\$labels,$name);
2028 # If no check array is specified, check the first by default
2029 $checked = $values[0] unless defined($checked) && $checked ne '';
2030 $name=$self->escapeHTML($name);
2032 my($other) = @other ? " @other" : '';
2034 my($checkit) = $checked eq $_ ? qq/ checked/ : '';
2037 $break = $XHTML ? "<br />" : "<br>";
2043 unless (defined($nolabels) && $nolabels) {
2045 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2046 $label = $self->escapeHTML($label,1);
2048 $_=$self->escapeHTML($_);
2049 push(@elements,$XHTML ? qq(<input type="radio" name="$name" value="$_"$checkit$other />${label}${break})
2050 : qq/<input type="radio" name="$name" value="$_"$checkit$other>${label}${break}/);
2052 $self->register_parameter($name);
2053 return wantarray ? @elements : join(' ',@elements)
2054 unless defined($columns) || defined($rows);
2055 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2060 #### Method: popup_menu
2061 # Create a popup menu.
2063 # $name -> Name for all the menu
2064 # $values -> A pointer to a regular array containing the
2065 # text of each menu item.
2066 # $default -> (optional) Default item to display
2067 # $labels -> (optional)
2068 # A pointer to an associative array of labels to print next to each checkbox
2069 # in the form $label{'value'}="Long explanatory label".
2070 # Otherwise the provided values are used as the labels.
2072 # A string containing the definition of a popup menu.
2074 'popup_menu' => <<'END_OF_FUNC',
2076 my($self,@p) = self_or_default(@_);
2078 my($name,$values,$default,$labels,$override,@other) =
2079 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,[OVERRIDE,FORCE]],@p);
2080 my($result,$selected);
2082 if (!$override && defined($self->param($name))) {
2083 $selected = $self->param($name);
2085 $selected = $default;
2087 $name=$self->escapeHTML($name);
2088 my($other) = @other ? " @other" : '';
2091 @values = $self->_set_values_and_labels($values,\$labels,$name);
2093 $result = qq/<select name="$name"$other>\n/;
2095 my($selectit) = defined($selected) ? ($selected eq $_ ? qq/selected/ : '' ) : '';
2097 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2098 my($value) = $self->escapeHTML($_);
2099 $label=$self->escapeHTML($label,1);
2100 $result .= "<option $selectit value=\"$value\">$label</option>\n";
2103 $result .= "</select>\n";
2109 #### Method: scrolling_list
2110 # Create a scrolling list.
2112 # $name -> name for the list
2113 # $values -> A pointer to a regular array containing the
2114 # values for each option line in the list.
2115 # $defaults -> (optional)
2116 # 1. If a pointer to a regular array of options,
2117 # then this will be used to decide which
2118 # lines to turn on by default.
2119 # 2. Otherwise holds the value of the single line to turn on.
2120 # $size -> (optional) Size of the list.
2121 # $multiple -> (optional) If set, allow multiple selections.
2122 # $labels -> (optional)
2123 # A pointer to an associative array of labels to print next to each checkbox
2124 # in the form $label{'value'}="Long explanatory label".
2125 # Otherwise the provided values are used as the labels.
2127 # A string containing the definition of a scrolling list.
2129 'scrolling_list' => <<'END_OF_FUNC',
2130 sub scrolling_list {
2131 my($self,@p) = self_or_default(@_);
2132 my($name,$values,$defaults,$size,$multiple,$labels,$override,@other)
2133 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2134 SIZE,MULTIPLE,LABELS,[OVERRIDE,FORCE]],@p);
2136 my($result,@values);
2137 @values = $self->_set_values_and_labels($values,\$labels,$name);
2139 $size = $size || scalar(@values);
2141 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2142 my($is_multiple) = $multiple ? qq/ multiple/ : '';
2143 my($has_size) = $size ? qq/ size="$size"/: '';
2144 my($other) = @other ? " @other" : '';
2146 $name=$self->escapeHTML($name);
2147 $result = qq/<select name="$name"$has_size$is_multiple$other>\n/;
2149 my($selectit) = $selected{$_} ? qq/selected/ : '';
2151 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2152 $label=$self->escapeHTML($label);
2153 my($value)=$self->escapeHTML($_,1);
2154 $result .= "<option $selectit value=\"$value\">$label</option>\n";
2156 $result .= "</select>\n";
2157 $self->register_parameter($name);
2165 # $name -> Name of the hidden field
2166 # @default -> (optional) Initial values of field (may be an array)
2168 # $default->[initial values of field]
2170 # A string containing a <INPUT TYPE="hidden" NAME="name" VALUE="value">
2172 'hidden' => <<'END_OF_FUNC',
2174 my($self,@p) = self_or_default(@_);
2176 # this is the one place where we departed from our standard
2177 # calling scheme, so we have to special-case (darn)
2179 my($name,$default,$override,@other) =
2180 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2182 my $do_override = 0;
2183 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2184 @value = ref($default) ? @{$default} : $default;
2185 $do_override = $override;
2187 foreach ($default,$override,@other) {
2188 push(@value,$_) if defined($_);
2192 # use previous values if override is not set
2193 my @prev = $self->param($name);
2194 @value = @prev if !$do_override && @prev;
2196 $name=$self->escapeHTML($name);
2198 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2199 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" />)
2200 : qq(<input type="hidden" name="$name" value="$_">);
2202 return wantarray ? @result : join('',@result);
2207 #### Method: image_button
2209 # $name -> Name of the button
2210 # $src -> URL of the image source
2211 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2213 # A string containing a <INPUT TYPE="image" NAME="name" SRC="url" ALIGN="alignment">
2215 'image_button' => <<'END_OF_FUNC',
2217 my($self,@p) = self_or_default(@_);
2219 my($name,$src,$alignment,@other) =
2220 rearrange([NAME,SRC,ALIGN],@p);
2222 my($align) = $alignment ? " align=\U$alignment" : '';
2223 my($other) = @other ? " @other" : '';
2224 $name=$self->escapeHTML($name);
2225 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2226 : qq/<input type="image" name="$name" src="$src"$align$other>/;
2231 #### Method: self_url
2232 # Returns a URL containing the current script and all its
2233 # param/value pairs arranged as a query. You can use this
2234 # to create a link that, when selected, will reinvoke the
2235 # script with all its state information preserved.
2237 'self_url' => <<'END_OF_FUNC',
2239 my($self,@p) = self_or_default(@_);
2240 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2245 # This is provided as a synonym to self_url() for people unfortunate
2246 # enough to have incorporated it into their programs already!
2247 'state' => <<'END_OF_FUNC',
2255 # Like self_url, but doesn't return the query string part of
2258 'url' => <<'END_OF_FUNC',
2260 my($self,@p) = self_or_default(@_);
2261 my ($relative,$absolute,$full,$path_info,$query,$base) =
2262 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE'],@p);
2264 $full++ if $base || !($relative || $absolute);
2266 my $path = $self->path_info;
2267 my $script_name = $self->script_name;
2269 # If anybody knows why I ever wrote this please tell me!
2270 # if (exists($ENV{REQUEST_URI})) {
2272 # $script_name = $ENV{REQUEST_URI};
2273 # # strip query string
2274 # substr($script_name,$index) = '' if ($index = index($script_name,'?')) >= 0;
2276 # if (exists($ENV{PATH_INFO})) {
2277 # (my $encoded_path = $ENV{PATH_INFO}) =~ s!([^a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;;
2278 # substr($script_name,$index) = '' if ($index = rindex($script_name,$encoded_path)) >= 0;
2281 # $script_name = $self->script_name;
2285 my $protocol = $self->protocol();
2286 $url = "$protocol://";
2287 my $vh = http('host');
2291 $url .= server_name();
2292 my $port = $self->server_port;
2294 unless (lc($protocol) eq 'http' && $port == 80)
2295 || (lc($protocol) eq 'https' && $port == 443);
2297 return $url if $base;
2298 $url .= $script_name;
2299 } elsif ($relative) {
2300 ($url) = $script_name =~ m!([^/]+)$!;
2301 } elsif ($absolute) {
2302 $url = $script_name;
2305 $url .= $path if $path_info and defined $path;
2306 $url .= "?" . $self->query_string if $query and $self->query_string;
2307 $url = '' unless defined $url;
2308 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/uc sprintf("%%%02x",ord($1))/eg;
2315 # Set or read a cookie from the specified name.
2316 # Cookie can then be passed to header().
2317 # Usual rules apply to the stickiness of -value.
2319 # -name -> name for this cookie (optional)
2320 # -value -> value of this cookie (scalar, array or hash)
2321 # -path -> paths for which this cookie is valid (optional)
2322 # -domain -> internet domain in which this cookie is valid (optional)
2323 # -secure -> if true, cookie only passed through secure channel (optional)
2324 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2326 'cookie' => <<'END_OF_FUNC',
2328 my($self,@p) = self_or_default(@_);
2329 my($name,$value,$path,$domain,$secure,$expires) =
2330 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2332 require CGI::Cookie;
2334 # if no value is supplied, then we retrieve the
2335 # value of the cookie, if any. For efficiency, we cache the parsed
2336 # cookies in our state variables.
2337 unless ( defined($value) ) {
2338 $self->{'.cookies'} = CGI::Cookie->fetch
2339 unless $self->{'.cookies'};
2341 # If no name is supplied, then retrieve the names of all our cookies.
2342 return () unless $self->{'.cookies'};
2343 return keys %{$self->{'.cookies'}} unless $name;
2344 return () unless $self->{'.cookies'}->{$name};
2345 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2348 # If we get here, we're creating a new cookie
2349 return undef unless defined($name) && $name ne ''; # this is an error
2352 push(@param,'-name'=>$name);
2353 push(@param,'-value'=>$value);
2354 push(@param,'-domain'=>$domain) if $domain;
2355 push(@param,'-path'=>$path) if $path;
2356 push(@param,'-expires'=>$expires) if $expires;
2357 push(@param,'-secure'=>$secure) if $secure;
2359 return new CGI::Cookie(@param);
2363 'parse_keywordlist' => <<'END_OF_FUNC',
2364 sub parse_keywordlist {
2365 my($self,$tosplit) = @_;
2366 $tosplit = unescape($tosplit); # unescape the keywords
2367 $tosplit=~tr/+/ /; # pluses to spaces
2368 my(@keywords) = split(/\s+/,$tosplit);
2373 'param_fetch' => <<'END_OF_FUNC',
2375 my($self,@p) = self_or_default(@_);
2376 my($name) = rearrange([NAME],@p);
2377 unless (exists($self->{$name})) {
2378 $self->add_parameter($name);
2379 $self->{$name} = [];
2382 return $self->{$name};
2386 ###############################################
2387 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2388 ###############################################
2390 #### Method: path_info
2391 # Return the extra virtual path information provided
2392 # after the URL (if any)
2394 'path_info' => <<'END_OF_FUNC',
2396 my ($self,$info) = self_or_default(@_);
2397 if (defined($info)) {
2398 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2399 $self->{'.path_info'} = $info;
2400 } elsif (! defined($self->{'.path_info'}) ) {
2401 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2402 $ENV{'PATH_INFO'} : '';
2404 # hack to fix broken path info in IIS
2405 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2408 return $self->{'.path_info'};
2413 #### Method: request_method
2414 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2416 'request_method' => <<'END_OF_FUNC',
2417 sub request_method {
2418 return $ENV{'REQUEST_METHOD'};
2422 #### Method: content_type
2423 # Returns the content_type string
2425 'content_type' => <<'END_OF_FUNC',
2427 return $ENV{'CONTENT_TYPE'};
2431 #### Method: path_translated
2432 # Return the physical path information provided
2433 # by the URL (if any)
2435 'path_translated' => <<'END_OF_FUNC',
2436 sub path_translated {
2437 return $ENV{'PATH_TRANSLATED'};
2442 #### Method: query_string
2443 # Synthesize a query string from our current
2446 'query_string' => <<'END_OF_FUNC',
2448 my($self) = self_or_default(@_);
2449 my($param,$value,@pairs);
2450 foreach $param ($self->param) {
2451 my($eparam) = escape($param);
2452 foreach $value ($self->param($param)) {
2453 $value = escape($value);
2454 next unless defined $value;
2455 push(@pairs,"$eparam=$value");
2458 foreach (keys %{$self->{'.fieldnames'}}) {
2459 push(@pairs,".cgifields=".escape("$_"));
2461 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2467 # Without parameters, returns an array of the
2468 # MIME types the browser accepts.
2469 # With a single parameter equal to a MIME
2470 # type, will return undef if the browser won't
2471 # accept it, 1 if the browser accepts it but
2472 # doesn't give a preference, or a floating point
2473 # value between 0.0 and 1.0 if the browser
2474 # declares a quantitative score for it.
2475 # This handles MIME type globs correctly.
2477 'Accept' => <<'END_OF_FUNC',
2479 my($self,$search) = self_or_CGI(@_);
2480 my(%prefs,$type,$pref,$pat);
2482 my(@accept) = split(',',$self->http('accept'));
2485 ($pref) = /q=(\d\.\d+|\d+)/;
2486 ($type) = m#(\S+/[^;]+)#;
2488 $prefs{$type}=$pref || 1;
2491 return keys %prefs unless $search;
2493 # if a search type is provided, we may need to
2494 # perform a pattern matching operation.
2495 # The MIME types use a glob mechanism, which
2496 # is easily translated into a perl pattern match
2498 # First return the preference for directly supported
2500 return $prefs{$search} if $prefs{$search};
2502 # Didn't get it, so try pattern matching.
2503 foreach (keys %prefs) {
2504 next unless /\*/; # not a pattern match
2505 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2506 $pat =~ s/\*/.*/g; # turn it into a pattern
2507 return $prefs{$_} if $search=~/$pat/;
2513 #### Method: user_agent
2514 # If called with no parameters, returns the user agent.
2515 # If called with one parameter, does a pattern match (case
2516 # insensitive) on the user agent.
2518 'user_agent' => <<'END_OF_FUNC',
2520 my($self,$match)=self_or_CGI(@_);
2521 return $self->http('user_agent') unless $match;
2522 return $self->http('user_agent') =~ /$match/i;
2527 #### Method: raw_cookie
2528 # Returns the magic cookies for the session.
2529 # The cookies are not parsed or altered in any way, i.e.
2530 # cookies are returned exactly as given in the HTTP
2531 # headers. If a cookie name is given, only that cookie's
2532 # value is returned, otherwise the entire raw cookie
2535 'raw_cookie' => <<'END_OF_FUNC',
2537 my($self,$key) = self_or_CGI(@_);
2539 require CGI::Cookie;
2541 if (defined($key)) {
2542 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2543 unless $self->{'.raw_cookies'};
2545 return () unless $self->{'.raw_cookies'};
2546 return () unless $self->{'.raw_cookies'}->{$key};
2547 return $self->{'.raw_cookies'}->{$key};
2549 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2553 #### Method: virtual_host
2554 # Return the name of the virtual_host, which
2555 # is not always the same as the server
2557 'virtual_host' => <<'END_OF_FUNC',
2559 my $vh = http('host') || server_name();
2560 $vh =~ s/:\d+$//; # get rid of port number
2565 #### Method: remote_host
2566 # Return the name of the remote host, or its IP
2567 # address if unavailable. If this variable isn't
2568 # defined, it returns "localhost" for debugging
2571 'remote_host' => <<'END_OF_FUNC',
2573 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2579 #### Method: remote_addr
2580 # Return the IP addr of the remote host.
2582 'remote_addr' => <<'END_OF_FUNC',
2584 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2589 #### Method: script_name
2590 # Return the partial URL to this script for
2591 # self-referencing scripts. Also see
2592 # self_url(), which returns a URL with all state information
2595 'script_name' => <<'END_OF_FUNC',
2597 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2598 # These are for debugging
2599 return "/$0" unless $0=~/^\//;
2605 #### Method: referer
2606 # Return the HTTP_REFERER: useful for generating
2609 'referer' => <<'END_OF_FUNC',
2611 my($self) = self_or_CGI(@_);
2612 return $self->http('referer');
2617 #### Method: server_name
2618 # Return the name of the server
2620 'server_name' => <<'END_OF_FUNC',
2622 return $ENV{'SERVER_NAME'} || 'localhost';
2626 #### Method: server_software
2627 # Return the name of the server software
2629 'server_software' => <<'END_OF_FUNC',
2630 sub server_software {
2631 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2635 #### Method: server_port
2636 # Return the tcp/ip port the server is running on
2638 'server_port' => <<'END_OF_FUNC',
2640 return $ENV{'SERVER_PORT'} || 80; # for debugging
2644 #### Method: server_protocol
2645 # Return the protocol (usually HTTP/1.0)
2647 'server_protocol' => <<'END_OF_FUNC',
2648 sub server_protocol {
2649 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2654 # Return the value of an HTTP variable, or
2655 # the list of variables if none provided
2657 'http' => <<'END_OF_FUNC',
2659 my ($self,$parameter) = self_or_CGI(@_);
2660 return $ENV{$parameter} if $parameter=~/^HTTP/;
2661 $parameter =~ tr/-/_/;
2662 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2664 foreach (keys %ENV) {
2665 push(@p,$_) if /^HTTP/;
2672 # Return the value of HTTPS
2674 'https' => <<'END_OF_FUNC',
2677 my ($self,$parameter) = self_or_CGI(@_);
2678 return $ENV{HTTPS} unless $parameter;
2679 return $ENV{$parameter} if $parameter=~/^HTTPS/;
2680 $parameter =~ tr/-/_/;
2681 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2683 foreach (keys %ENV) {
2684 push(@p,$_) if /^HTTPS/;
2690 #### Method: protocol
2691 # Return the protocol (http or https currently)
2693 'protocol' => <<'END_OF_FUNC',
2697 return 'https' if uc($self->https()) eq 'ON';
2698 return 'https' if $self->server_port == 443;
2699 my $prot = $self->server_protocol;
2700 my($protocol,$version) = split('/',$prot);
2701 return "\L$protocol\E";
2705 #### Method: remote_ident
2706 # Return the identity of the remote user
2707 # (but only if his host is running identd)
2709 'remote_ident' => <<'END_OF_FUNC',
2711 return $ENV{'REMOTE_IDENT'};
2716 #### Method: auth_type
2717 # Return the type of use verification/authorization in use, if any.
2719 'auth_type' => <<'END_OF_FUNC',
2721 return $ENV{'AUTH_TYPE'};
2726 #### Method: remote_user
2727 # Return the authorization name used for user
2730 'remote_user' => <<'END_OF_FUNC',
2732 return $ENV{'REMOTE_USER'};
2737 #### Method: user_name
2738 # Try to return the remote user's name by hook or by
2741 'user_name' => <<'END_OF_FUNC',
2743 my ($self) = self_or_CGI(@_);
2744 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2748 #### Method: nosticky
2749 # Set or return the NOSTICKY global flag
2751 'nosticky' => <<'END_OF_FUNC',
2753 my ($self,$param) = self_or_CGI(@_);
2754 $CGI::NOSTICKY = $param if defined($param);
2755 return $CGI::NOSTICKY;
2760 # Set or return the NPH global flag
2762 'nph' => <<'END_OF_FUNC',
2764 my ($self,$param) = self_or_CGI(@_);
2765 $CGI::NPH = $param if defined($param);
2770 #### Method: private_tempfiles
2771 # Set or return the private_tempfiles global flag
2773 'private_tempfiles' => <<'END_OF_FUNC',
2774 sub private_tempfiles {
2775 my ($self,$param) = self_or_CGI(@_);
2776 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
2777 return $CGI::PRIVATE_TEMPFILES;
2781 #### Method: default_dtd
2782 # Set or return the default_dtd global
2784 'default_dtd' => <<'END_OF_FUNC',
2786 my ($self,$param,$param2) = self_or_CGI(@_);
2787 if (defined $param2 && defined $param) {
2788 $CGI::DEFAULT_DTD = [ $param, $param2 ];
2789 } elsif (defined $param) {
2790 $CGI::DEFAULT_DTD = $param;
2792 return $CGI::DEFAULT_DTD;
2796 # -------------- really private subroutines -----------------
2797 'previous_or_default' => <<'END_OF_FUNC',
2798 sub previous_or_default {
2799 my($self,$name,$defaults,$override) = @_;
2802 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2803 defined($self->param($name)) ) ) {
2804 grep($selected{$_}++,$self->param($name));
2805 } elsif (defined($defaults) && ref($defaults) &&
2806 (ref($defaults) eq 'ARRAY')) {
2807 grep($selected{$_}++,@{$defaults});
2809 $selected{$defaults}++ if defined($defaults);
2816 'register_parameter' => <<'END_OF_FUNC',
2817 sub register_parameter {
2818 my($self,$param) = @_;
2819 $self->{'.parametersToAdd'}->{$param}++;
2823 'get_fields' => <<'END_OF_FUNC',
2826 return $self->CGI::hidden('-name'=>'.cgifields',
2827 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2832 'read_from_cmdline' => <<'END_OF_FUNC',
2833 sub read_from_cmdline {
2836 if ($DEBUG && @ARGV) {
2838 } elsif ($DEBUG > 1) {
2839 require "shellwords.pl";
2840 print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2841 chomp(@lines = <STDIN>); # remove newlines
2842 $input = join(" ",@lines);
2843 @words = &shellwords($input);
2850 if ("@words"=~/=/) {
2851 $query_string = join('&',@words);
2853 $query_string = join('+',@words);
2855 return $query_string;
2860 # subroutine: read_multipart
2862 # Read multipart data and store it into our parameters.
2863 # An interesting feature is that if any of the parts is a file, we
2864 # create a temporary file and open up a filehandle on it so that the
2865 # caller can read from it if necessary.
2867 'read_multipart' => <<'END_OF_FUNC',
2868 sub read_multipart {
2869 my($self,$boundary,$length,$filehandle) = @_;
2870 my($buffer) = $self->new_MultipartBuffer($boundary,$length,$filehandle);
2871 return unless $buffer;
2874 while (!$buffer->eof) {
2875 %header = $buffer->readHeader;
2878 $self->cgi_error("400 Bad request (malformed multipart POST)");
2882 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
2884 # Bug: Netscape doesn't escape quotation marks in file names!!!
2885 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\"]*)"?/;
2887 # add this parameter to our list
2888 $self->add_parameter($param);
2890 # If no filename specified, then just read the data and assign it
2891 # to our parameter list.
2892 if ( !defined($filename) || $filename eq '' ) {
2893 my($value) = $buffer->readBody;
2894 push(@{$self->{$param}},$value);
2898 my ($tmpfile,$tmp,$filehandle);
2900 # If we get here, then we are dealing with a potentially large
2901 # uploaded form. Save the data to a temporary file, then open
2902 # the file for reading.
2904 # skip the file if uploads disabled
2905 if ($DISABLE_UPLOADS) {
2906 while (defined($data = $buffer->read)) { }
2910 # choose a relatively unpredictable tmpfile sequence number
2911 my $seqno = unpack("%16C*",join('',localtime,values %ENV));
2912 for (my $cnt=10;$cnt>0;$cnt--) {
2913 next unless $tmpfile = new TempFile($seqno);
2914 $tmp = $tmpfile->as_string;
2915 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
2916 $seqno += int rand(100);
2918 die "CGI open of tmpfile: $!\n" unless $filehandle;
2919 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2923 while (defined($data = $buffer->read)) {
2924 print $filehandle $data;
2927 # back up to beginning of file
2928 seek($filehandle,0,0);
2929 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2931 # Save some information about the uploaded file where we can get
2933 $self->{'.tmpfiles'}->{fileno($filehandle)}= {
2937 push(@{$self->{$param}},$filehandle);
2943 'upload' =><<'END_OF_FUNC',
2945 my($self,$param_name) = self_or_default(@_);
2946 my @param = grep(ref && fileno($_), $self->param($param_name));
2947 return unless @param;
2948 return wantarray ? @param : $param[0];
2952 'tmpFileName' => <<'END_OF_FUNC',
2954 my($self,$filename) = self_or_default(@_);
2955 return $self->{'.tmpfiles'}->{fileno($filename)}->{name} ?
2956 $self->{'.tmpfiles'}->{fileno($filename)}->{name}->as_string
2961 'uploadInfo' => <<'END_OF_FUNC',
2963 my($self,$filename) = self_or_default(@_);
2964 return $self->{'.tmpfiles'}->{fileno($filename)}->{info};
2968 # internal routine, don't use
2969 '_set_values_and_labels' => <<'END_OF_FUNC',
2970 sub _set_values_and_labels {
2973 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
2974 return $self->param($n) if !defined($v);
2975 return $v if !ref($v);
2976 return ref($v) eq 'HASH' ? keys %$v : @$v;
2980 '_compile_all' => <<'END_OF_FUNC',
2983 next if defined(&$_);
2984 $AUTOLOAD = "CGI::$_";
2994 #########################################################
2995 # Globals and stubs for other packages that we use.
2996 #########################################################
2998 ################### Fh -- lightweight filehandle ###############
3007 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3009 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3010 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3012 'asString' => <<'END_OF_FUNC',
3015 # get rid of package name
3016 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
3017 $i =~ s/%(..)/ chr(hex($1)) /eg;
3020 # This was an extremely clever patch that allowed "use strict refs".
3021 # Unfortunately it relied on another bug that caused leaky file descriptors.
3022 # The underlying bug has been fixed, so this no longer works. However
3023 # "strict refs" still works for some reason.
3025 # return ${*{$self}{SCALAR}};
3030 'compare' => <<'END_OF_FUNC',
3034 return "$self" cmp $value;
3038 'new' => <<'END_OF_FUNC',
3040 my($pack,$name,$file,$delete) = @_;
3041 require Fcntl unless defined &Fcntl::O_RDWR;
3042 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3043 my $fv = ++$FH . $safename;
3044 my $ref = \*{"Fh::$fv"};
3045 sysopen($ref,$file,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3046 unlink($file) if $delete;
3047 CORE::delete $Fh::{$fv};
3048 return bless $ref,$pack;
3052 'DESTROY' => <<'END_OF_FUNC',
3062 ######################## MultipartBuffer ####################
3063 package MultipartBuffer;
3065 # how many bytes to read at a time. We use
3066 # a 4K buffer by default.
3067 $INITIAL_FILLUNIT = 1024 * 4;
3068 $TIMEOUT = 240*60; # 4 hour timeout for big files
3069 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3072 #reuse the autoload function
3073 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3075 # avoid autoloader warnings
3078 ###############################################################################
3079 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3080 ###############################################################################
3081 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3082 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3085 'new' => <<'END_OF_FUNC',
3087 my($package,$interface,$boundary,$length,$filehandle) = @_;
3088 $FILLUNIT = $INITIAL_FILLUNIT;
3091 my($package) = caller;
3092 # force into caller's package if necessary
3093 $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
3095 $IN = "main::STDIN" unless $IN;
3097 $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
3099 # If the user types garbage into the file upload field,
3100 # then Netscape passes NOTHING to the server (not good).
3101 # We may hang on this read in that case. So we implement
3102 # a read timeout. If nothing is ready to read
3103 # by then, we return.
3105 # Netscape seems to be a little bit unreliable
3106 # about providing boundary strings.
3107 my $boundary_read = 0;
3110 # Under the MIME spec, the boundary consists of the
3111 # characters "--" PLUS the Boundary string
3113 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3114 # the two extra hyphens. We do a special case here on the user-agent!!!!
3115 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac');
3117 } else { # otherwise we find it ourselves
3119 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3120 $boundary = <$IN>; # BUG: This won't work correctly under mod_perl
3121 $length -= length($boundary);
3122 chomp($boundary); # remove the CRLF
3123 $/ = $old; # restore old line separator
3127 my $self = {LENGTH=>$length,
3128 BOUNDARY=>$boundary,
3130 INTERFACE=>$interface,
3134 $FILLUNIT = length($boundary)
3135 if length($boundary) > $FILLUNIT;
3137 my $retval = bless $self,ref $package || $package;
3139 # Read the preamble and the topmost (boundary) line plus the CRLF.
3140 unless ($boundary_read) {
3141 while ($self->read(0)) { }
3143 die "Malformed multipart POST\n" if $self->eof;
3149 'readHeader' => <<'END_OF_FUNC',
3156 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
3159 $self->fillBuffer($FILLUNIT);
3160 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3161 $ok++ if $self->{BUFFER} eq '';
3162 $bad++ if !$ok && $self->{LENGTH} <= 0;
3163 # this was a bad idea
3164 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3165 } until $ok || $bad;
3168 my($header) = substr($self->{BUFFER},0,$end+2);
3169 substr($self->{BUFFER},0,$end+4) = '';
3173 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3174 # (Folding Long Header Fields), 3.4.3 (Comments)
3175 # and 3.4.5 (Quoted-Strings).
3177 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3178 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3179 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3180 my ($field_name,$field_value) = ($1,$2); # avoid taintedness
3181 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3182 $return{$field_name}=$field_value;
3188 # This reads and returns the body as a single scalar value.
3189 'readBody' => <<'END_OF_FUNC',
3194 while (defined($data = $self->read)) {
3195 $returnval .= $data;
3201 # This will read $bytes or until the boundary is hit, whichever happens
3202 # first. After the boundary is hit, we return undef. The next read will
3203 # skip over the boundary and begin reading again;
3204 'read' => <<'END_OF_FUNC',
3206 my($self,$bytes) = @_;
3208 # default number of bytes to read
3209 $bytes = $bytes || $FILLUNIT;
3211 # Fill up our internal buffer in such a way that the boundary
3212 # is never split between reads.
3213 $self->fillBuffer($bytes);
3215 # Find the boundary in the buffer (it may not be there).
3216 my $start = index($self->{BUFFER},$self->{BOUNDARY});
3217 # protect against malformed multipart POST operations
3218 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3220 # If the boundary begins the data, then skip past it
3224 # clear us out completely if we've hit the last boundary.
3225 if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
3231 # just remove the boundary.
3232 substr($self->{BUFFER},0,length($self->{BOUNDARY}))='';
3233 $self->{BUFFER} =~ s/^\012\015?//;
3238 if ($start > 0) { # read up to the boundary
3239 $bytesToReturn = $start > $bytes ? $bytes : $start;
3240 } else { # read the requested number of bytes
3241 # leave enough bytes in the buffer to allow us to read
3242 # the boundary. Thanks to Kevin Hendrick for finding
3244 $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
3247 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3248 substr($self->{BUFFER},0,$bytesToReturn)='';
3250 # If we hit the boundary, remove the CRLF from the end.
3251 return ($start > 0) ? substr($returnval,0,-2) : $returnval;
3256 # This fills up our internal buffer in such a way that the
3257 # boundary is never split between reads
3258 'fillBuffer' => <<'END_OF_FUNC',
3260 my($self,$bytes) = @_;
3261 return unless $self->{LENGTH};
3263 my($boundaryLength) = length($self->{BOUNDARY});
3264 my($bufferLength) = length($self->{BUFFER});
3265 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3266 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3268 # Try to read some data. We may hang here if the browser is screwed up.
3269 my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
3273 $self->{BUFFER} = '' unless defined $self->{BUFFER};
3275 # An apparent bug in the Apache server causes the read()
3276 # to return zero bytes repeatedly without blocking if the
3277 # remote user aborts during a file transfer. I don't know how
3278 # they manage this, but the workaround is to abort if we get
3279 # more than SPIN_LOOP_MAX consecutive zero reads.
3280 if ($bytesRead == 0) {
3281 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3282 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3284 $self->{ZERO_LOOP_COUNTER}=0;
3287 $self->{LENGTH} -= $bytesRead;
3292 # Return true when we've finished reading
3293 'eof' => <<'END_OF_FUNC'
3296 return 1 if (length($self->{BUFFER}) == 0)
3297 && ($self->{LENGTH} <= 0);
3305 ####################################################################################
3306 ################################## TEMPORARY FILES #################################
3307 ####################################################################################
3311 $MAC = $CGI::OS eq 'MACINTOSH';
3312 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3313 unless ($TMPDIRECTORY) {
3314 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3315 "C:${SL}temp","${SL}tmp","${SL}temp",
3316 "${vol}${SL}Temporary Items",
3317 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3318 "C:${SL}system${SL}temp");
3319 unshift(@TEMP,$ENV{'TMPDIR'}) if exists $ENV{'TMPDIR'};
3321 # this feature was supposed to provide per-user tmpfiles, but
3322 # it is problematic.
3323 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3324 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3325 # : can generate a 'getpwuid() not implemented' exception, even though
3326 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3327 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3328 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3331 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3335 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3338 # cute feature, but overload implementation broke it
3339 # %OVERLOAD = ('""'=>'as_string');
3340 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3342 ###############################################################################
3343 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3344 ###############################################################################
3345 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3346 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3349 'new' => <<'END_OF_FUNC',
3351 my($package,$sequence) = @_;
3353 for (my $i = 0; $i < $MAXTRIES; $i++) {
3354 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3356 # untaint the darn thing
3357 return unless $filename =~ m!^([a-zA-Z0-9_ '":/.\$\\-]+)$!;
3359 return bless \$filename;
3363 'DESTROY' => <<'END_OF_FUNC',
3366 unlink $$self; # get rid of the file
3370 'as_string' => <<'END_OF_FUNC'
3382 # We get a whole bunch of warnings about "possibly uninitialized variables"
3383 # when running with the -w switch. Touch them all once to get rid of the
3384 # warnings. This is ugly and I hate it.
3389 $MultipartBuffer::SPIN_LOOP_MAX;
3390 $MultipartBuffer::CRLF;
3391 $MultipartBuffer::TIMEOUT;
3392 $MultipartBuffer::INITIAL_FILLUNIT;
3403 CGI - Simple Common Gateway Interface Class
3407 # CGI script that creates a fill-out form
3408 # and echoes back its values.
3410 use CGI qw/:standard/;
3412 start_html('A Simple Example'),
3413 h1('A Simple Example'),
3415 "What's your name? ",textfield('name'),p,
3416 "What's the combination?", p,
3417 checkbox_group(-name=>'words',
3418 -values=>['eenie','meenie','minie','moe'],
3419 -defaults=>['eenie','minie']), p,
3420 "What's your favorite color? ",
3421 popup_menu(-name=>'color',
3422 -values=>['red','green','blue','chartreuse']),p,
3428 print "Your name is",em(param('name')),p,
3429 "The keywords are: ",em(join(", ",param('words'))),p,
3430 "Your favorite color is ",em(param('color')),
3436 This perl library uses perl5 objects to make it easy to create Web
3437 fill-out forms and parse their contents. This package defines CGI
3438 objects, entities that contain the values of the current query string
3439 and other state variables. Using a CGI object's methods, you can
3440 examine keywords and parameters passed to your script, and create
3441 forms whose initial values are taken from the current query (thereby
3442 preserving state information). The module provides shortcut functions
3443 that produce boilerplate HTML, reducing typing and coding errors. It
3444 also provides functionality for some of the more advanced features of
3445 CGI scripting, including support for file uploads, cookies, cascading
3446 style sheets, server push, and frames.
3448 CGI.pm also provides a simple function-oriented programming style for
3449 those who don't need its object-oriented features.
3451 The current version of CGI.pm is available at
3453 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3454 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3458 =head2 PROGRAMMING STYLE
3460 There are two styles of programming with CGI.pm, an object-oriented
3461 style and a function-oriented style. In the object-oriented style you
3462 create one or more CGI objects and then use object methods to create
3463 the various elements of the page. Each CGI object starts out with the
3464 list of named parameters that were passed to your CGI script by the
3465 server. You can modify the objects, save them to a file or database
3466 and recreate them. Because each object corresponds to the "state" of
3467 the CGI script, and because each object's parameter list is
3468 independent of the others, this allows you to save the state of the
3469 script and restore it later.
3471 For example, using the object oriented style, here is how you create
3472 a simple "Hello World" HTML page:
3474 #!/usr/local/bin/perl -w
3475 use CGI; # load CGI routines
3476 $q = new CGI; # create new CGI object
3477 print $q->header, # create the HTTP header
3478 $q->start_html('hello world'), # start the HTML
3479 $q->h1('hello world'), # level 1 header
3480 $q->end_html; # end the HTML
3482 In the function-oriented style, there is one default CGI object that
3483 you rarely deal with directly. Instead you just call functions to
3484 retrieve CGI parameters, create HTML tags, manage cookies, and so
3485 on. This provides you with a cleaner programming interface, but
3486 limits you to using one CGI object at a time. The following example
3487 prints the same page, but uses the function-oriented interface.
3488 The main differences are that we now need to import a set of functions
3489 into our name space (usually the "standard" functions), and we don't
3490 need to create the CGI object.
3492 #!/usr/local/bin/perl
3493 use CGI qw/:standard/; # load standard CGI routines
3494 print header, # create the HTTP header
3495 start_html('hello world'), # start the HTML
3496 h1('hello world'), # level 1 header
3497 end_html; # end the HTML
3499 The examples in this document mainly use the object-oriented style.
3500 See HOW TO IMPORT FUNCTIONS for important information on
3501 function-oriented programming in CGI.pm
3503 =head2 CALLING CGI.PM ROUTINES
3505 Most CGI.pm routines accept several arguments, sometimes as many as 20
3506 optional ones! To simplify this interface, all routines use a named
3507 argument calling style that looks like this:
3509 print $q->header(-type=>'image/gif',-expires=>'+3d');
3511 Each argument name is preceded by a dash. Neither case nor order
3512 matters in the argument list. -type, -Type, and -TYPE are all
3513 acceptable. In fact, only the first argument needs to begin with a
3514 dash. If a dash is present in the first argument, CGI.pm assumes
3515 dashes for the subsequent ones.
3517 Several routines are commonly called with just one argument. In the
3518 case of these routines you can provide the single argument without an
3519 argument name. header() happens to be one of these routines. In this
3520 case, the single argument is the document type.
3522 print $q->header('text/html');
3524 Other such routines are documented below.
3526 Sometimes named arguments expect a scalar, sometimes a reference to an
3527 array, and sometimes a reference to a hash. Often, you can pass any
3528 type of argument and the routine will do whatever is most appropriate.
3529 For example, the param() routine is used to set a CGI parameter to a
3530 single or a multi-valued value. The two cases are shown below:
3532 $q->param(-name=>'veggie',-value=>'tomato');
3533 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
3535 A large number of routines in CGI.pm actually aren't specifically
3536 defined in the module, but are generated automatically as needed.
3537 These are the "HTML shortcuts," routines that generate HTML tags for
3538 use in dynamically-generated pages. HTML tags have both attributes
3539 (the attribute="value" pairs within the tag itself) and contents (the
3540 part between the opening and closing pairs.) To distinguish between
3541 attributes and contents, CGI.pm uses the convention of passing HTML
3542 attributes as a hash reference as the first argument, and the
3543 contents, if any, as any subsequent arguments. It works out like
3549 h1('some','contents'); <H1>some contents</H1>
3550 h1({-align=>left}); <H1 ALIGN="LEFT">
3551 h1({-align=>left},'contents'); <H1 ALIGN="LEFT">contents</H1>
3553 HTML tags are described in more detail later.
3555 Many newcomers to CGI.pm are puzzled by the difference between the
3556 calling conventions for the HTML shortcuts, which require curly braces
3557 around the HTML tag attributes, and the calling conventions for other
3558 routines, which manage to generate attributes without the curly
3559 brackets. Don't be confused. As a convenience the curly braces are
3560 optional in all but the HTML shortcuts. If you like, you can use
3561 curly braces when calling any routine that takes named arguments. For
3564 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3566 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3567 names conflict with built-in Perl functions. The most frequent of
3568 these is the -values argument, used to create multi-valued menus,
3569 radio button clusters and the like. To get around this warning, you
3570 have several choices:
3576 Use another name for the argument, if one is available.
3577 For example, -value is an alias for -values.
3581 Change the capitalization, e.g. -Values
3585 Put quotes around the argument name, e.g. '-values'
3589 Many routines will do something useful with a named argument that it
3590 doesn't recognize. For example, you can produce non-standard HTTP
3591 header fields by providing them as named arguments:
3593 print $q->header(-type => 'text/html',
3594 -cost => 'Three smackers',
3595 -annoyance_level => 'high',
3596 -complaints_to => 'bit bucket');
3598 This will produce the following nonstandard HTTP header:
3601 Cost: Three smackers
3602 Annoyance-level: high
3603 Complaints-to: bit bucket
3604 Content-type: text/html
3606 Notice the way that underscores are translated automatically into
3607 hyphens. HTML-generating routines perform a different type of
3610 This feature allows you to keep up with the rapidly changing HTTP and
3613 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
3617 This will parse the input (from both POST and GET methods) and store
3618 it into a perl5 object called $query.
3620 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
3622 $query = new CGI(INPUTFILE);
3624 If you provide a file handle to the new() method, it will read
3625 parameters from the file (or STDIN, or whatever). The file can be in
3626 any of the forms describing below under debugging (i.e. a series of
3627 newline delimited TAG=VALUE pairs will work). Conveniently, this type
3628 of file is created by the save() method (see below). Multiple records
3629 can be saved and restored.
3631 Perl purists will be pleased to know that this syntax accepts
3632 references to file handles, or even references to filehandle globs,
3633 which is the "official" way to pass a filehandle:
3635 $query = new CGI(\*STDIN);
3637 You can also initialize the CGI object with a FileHandle or IO::File
3640 If you are using the function-oriented interface and want to
3641 initialize CGI state from a file handle, the way to do this is with
3642 B<restore_parameters()>. This will (re)initialize the
3643 default CGI object from the indicated file handle.
3645 open (IN,"test.in") || die;
3646 restore_parameters(IN);
3649 You can also initialize the query object from an associative array
3652 $query = new CGI( {'dinosaur'=>'barney',
3653 'song'=>'I love you',
3654 'friends'=>[qw/Jessica George Nancy/]}
3657 or from a properly formatted, URL-escaped query string:
3659 $query = new CGI('dinosaur=barney&color=purple');
3661 or from a previously existing CGI object (currently this clones the
3662 parameter list, but none of the other object-specific fields, such as
3665 $old_query = new CGI;
3666 $new_query = new CGI($old_query);
3668 To create an empty query, initialize it from an empty string or hash:
3670 $empty_query = new CGI("");
3674 $empty_query = new CGI({});
3676 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
3678 @keywords = $query->keywords
3680 If the script was invoked as the result of an <ISINDEX> search, the
3681 parsed keywords can be obtained as an array using the keywords() method.
3683 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
3685 @names = $query->param
3687 If the script was invoked with a parameter list
3688 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
3689 will return the parameter names as a list. If the script was invoked
3690 as an <ISINDEX> script and contains a string without ampersands
3691 (e.g. "value1+value2+value3") , there will be a single parameter named
3692 "keywords" containing the "+"-delimited keywords.
3694 NOTE: As of version 1.5, the array of parameter names returned will
3695 be in the same order as they were submitted by the browser.
3696 Usually this order is the same as the order in which the
3697 parameters are defined in the form (however, this isn't part
3698 of the spec, and so isn't guaranteed).
3700 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
3702 @values = $query->param('foo');
3706 $value = $query->param('foo');
3708 Pass the param() method a single argument to fetch the value of the
3709 named parameter. If the parameter is multivalued (e.g. from multiple
3710 selections in a scrolling list), you can ask to receive an array. Otherwise
3711 the method will return a single value.
3713 If a value is not given in the query string, as in the queries
3714 "name1=&name2=" or "name1&name2", it will be returned as an empty
3715 string. This feature is new in 2.63.
3717 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
3719 $query->param('foo','an','array','of','values');
3721 This sets the value for the named parameter 'foo' to an array of
3722 values. This is one way to change the value of a field AFTER
3723 the script has been invoked once before. (Another way is with
3724 the -override parameter accepted by all methods that generate
3727 param() also recognizes a named parameter style of calling described
3728 in more detail later:
3730 $query->param(-name=>'foo',-values=>['an','array','of','values']);
3734 $query->param(-name=>'foo',-value=>'the value');
3736 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
3738 $query->append(-name=>'foo',-values=>['yet','more','values']);
3740 This adds a value or list of values to the named parameter. The
3741 values are appended to the end of the parameter if it already exists.
3742 Otherwise the parameter is created. Note that this method only
3743 recognizes the named argument calling syntax.
3745 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
3747 $query->import_names('R');
3749 This creates a series of variables in the 'R' namespace. For example,
3750 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
3751 If no namespace is given, this method will assume 'Q'.
3752 WARNING: don't import anything into 'main'; this is a major security
3755 In older versions, this method was called B<import()>. As of version 2.20,
3756 this name has been removed completely to avoid conflict with the built-in
3757 Perl module B<import> operator.
3759 =head2 DELETING A PARAMETER COMPLETELY:
3761 $query->delete('foo');
3763 This completely clears a parameter. It sometimes useful for
3764 resetting parameters that you don't want passed down between
3767 If you are using the function call interface, use "Delete()" instead
3768 to avoid conflicts with Perl's built-in delete operator.
3770 =head2 DELETING ALL PARAMETERS:
3772 $query->delete_all();
3774 This clears the CGI object completely. It might be useful to ensure
3775 that all the defaults are taken when you create a fill-out form.
3777 Use Delete_all() instead if you are using the function call interface.
3779 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
3781 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
3782 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
3784 If you need access to the parameter list in a way that isn't covered
3785 by the methods above, you can obtain a direct reference to it by
3786 calling the B<param_fetch()> method with the name of the . This
3787 will return an array reference to the named parameters, which you then
3788 can manipulate in any way you like.
3790 You can also use a named argument style using the B<-name> argument.
3792 =head2 FETCHING THE PARAMETER LIST AS A HASH:
3795 print $params->{'address'};
3796 @foo = split("\0",$params->{'foo'});
3802 Many people want to fetch the entire parameter list as a hash in which
3803 the keys are the names of the CGI parameters, and the values are the
3804 parameters' values. The Vars() method does this. Called in a scalar
3805 context, it returns the parameter list as a tied hash reference.
3806 Changing a key changes the value of the parameter in the underlying
3807 CGI parameter list. Called in a list context, it returns the
3808 parameter list as an ordinary hash. This allows you to read the
3809 contents of the parameter list, but not to change it.
3811 When using this, the thing you must watch out for are multivalued CGI
3812 parameters. Because a hash cannot distinguish between scalar and
3813 list context, multivalued parameters will be returned as a packed
3814 string, separated by the "\0" (null) character. You must split this
3815 packed string in order to get at the individual values. This is the
3816 convention introduced long ago by Steve Brenner in his cgi-lib.pl
3817 module for Perl version 4.
3819 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
3820 function calls (also see the section on CGI-LIB compatibility).
3822 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
3824 $query->save(FILEHANDLE)
3826 This will write the current state of the form to the provided
3827 filehandle. You can read it back in by providing a filehandle
3828 to the new() method. Note that the filehandle can be a file, a pipe,
3831 The format of the saved file is:
3839 Both name and value are URL escaped. Multi-valued CGI parameters are
3840 represented as repeated names. A session record is delimited by a
3841 single = symbol. You can write out multiple records and read them
3842 back in with several calls to B<new>. You can do this across several
3843 sessions by opening the file in append mode, allowing you to create
3844 primitive guest books, or to keep a history of users' queries. Here's
3845 a short example of creating multiple session records:
3849 open (OUT,">>test.out") || die;
3851 foreach (0..$records) {
3853 $q->param(-name=>'counter',-value=>$_);
3858 # reopen for reading
3859 open (IN,"test.out") || die;
3861 my $q = new CGI(IN);
3862 print $q->param('counter'),"\n";
3865 The file format used for save/restore is identical to that used by the
3866 Whitehead Genome Center's data exchange format "Boulderio", and can be
3867 manipulated and even databased using Boulderio utilities. See
3869 http://stein.cshl.org/boulder/
3871 for further details.
3873 If you wish to use this method from the function-oriented (non-OO)
3874 interface, the exported name for this method is B<save_parameters()>.
3876 =head2 RETRIEVING CGI ERRORS
3878 Errors can occur while processing user input, particularly when
3879 processing uploaded files. When these errors occur, CGI will stop
3880 processing and return an empty parameter list. You can test for
3881 the existence and nature of errors using the I<cgi_error()> function.
3882 The error messages are formatted as HTTP status codes. You can either
3883 incorporate the error text into an HTML page, or use it as the value
3886 my $error = $q->cgi_error;
3888 print $q->header(-status=>$error),
3889 $q->start_html('Problems'),
3890 $q->h2('Request not processed'),
3895 When using the function-oriented interface (see the next section),
3896 errors may only occur the first time you call I<param()>. Be ready
3899 =head2 USING THE FUNCTION-ORIENTED INTERFACE
3901 To use the function-oriented interface, you must specify which CGI.pm
3902 routines or sets of routines to import into your script's namespace.
3903 There is a small overhead associated with this importation, but it
3906 use CGI <list of methods>;
3908 The listed methods will be imported into the current package; you can
3909 call them directly without creating a CGI object first. This example
3910 shows how to import the B<param()> and B<header()>
3911 methods, and then use them directly:
3913 use CGI 'param','header';
3914 print header('text/plain');
3915 $zipcode = param('zipcode');
3917 More frequently, you'll import common sets of functions by referring
3918 to the groups by name. All function sets are preceded with a ":"
3919 character as in ":html3" (for tags defined in the HTML 3 standard).
3921 Here is a list of the function sets you can import:
3927 Import all CGI-handling methods, such as B<param()>, B<path_info()>
3932 Import all fill-out form generating methods, such as B<textfield()>.
3936 Import all methods that generate HTML 2.0 standard elements.
3940 Import all methods that generate HTML 3.0 proposed elements (such as
3941 <table>, <super> and <sub>).
3945 Import all methods that generate Netscape-specific HTML extensions.
3949 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
3954 Import "standard" features, 'html2', 'html3', 'form' and 'cgi'.
3958 Import all the available methods. For the full list, see the CGI.pm
3959 code, where the variable %EXPORT_TAGS is defined.
3963 If you import a function name that is not part of CGI.pm, the module
3964 will treat it as a new HTML tag and generate the appropriate
3965 subroutine. You can then use it like any other HTML tag. This is to
3966 provide for the rapidly-evolving HTML "standard." For example, say
3967 Microsoft comes out with a new tag called <GRADIENT> (which causes the
3968 user's desktop to be flooded with a rotating gradient fill until his
3969 machine reboots). You don't need to wait for a new version of CGI.pm
3970 to start using it immediately:
3972 use CGI qw/:standard :html3 gradient/;
3973 print gradient({-start=>'red',-end=>'blue'});
3975 Note that in the interests of execution speed CGI.pm does B<not> use
3976 the standard L<Exporter> syntax for specifying load symbols. This may
3977 change in the future.
3979 If you import any of the state-maintaining CGI or form-generating
3980 methods, a default CGI object will be created and initialized
3981 automatically the first time you use any of the methods that require
3982 one to be present. This includes B<param()>, B<textfield()>,
3983 B<submit()> and the like. (If you need direct access to the CGI
3984 object, you can find it in the global variable B<$CGI::Q>). By
3985 importing CGI.pm methods, you can create visually elegant scripts:
3987 use CGI qw/:standard/;
3990 start_html('Simple Script'),
3991 h1('Simple Script'),
3993 "What's your name? ",textfield('name'),p,
3994 "What's the combination?",
3995 checkbox_group(-name=>'words',
3996 -values=>['eenie','meenie','minie','moe'],
3997 -defaults=>['eenie','moe']),p,
3998 "What's your favorite color?",
3999 popup_menu(-name=>'color',
4000 -values=>['red','green','blue','chartreuse']),p,
4007 "Your name is ",em(param('name')),p,
4008 "The keywords are: ",em(join(", ",param('words'))),p,
4009 "Your favorite color is ",em(param('color')),".\n";
4015 In addition to the function sets, there are a number of pragmas that
4016 you can import. Pragmas, which are always preceded by a hyphen,
4017 change the way that CGI.pm functions in various ways. Pragmas,
4018 function sets, and individual functions can all be imported in the
4019 same use() line. For example, the following use statement imports the
4020 standard set of functions and enables debugging mode (pragma
4023 use CGI qw/:standard -debug/;
4025 The current list of pragmas is as follows:
4031 When you I<use CGI -any>, then any method that the query object
4032 doesn't recognize will be interpreted as a new HTML tag. This allows
4033 you to support the next I<ad hoc> Netscape or Microsoft HTML
4034 extension. This lets you go wild with new and unsupported tags:
4038 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4040 Since using <cite>any</cite> causes any mistyped method name
4041 to be interpreted as an HTML tag, use it with care or not at
4046 This causes the indicated autoloaded methods to be compiled up front,
4047 rather than deferred to later. This is useful for scripts that run
4048 for an extended period of time under FastCGI or mod_perl, and for
4049 those destined to be crunched by Malcom Beattie's Perl compiler. Use
4050 it in conjunction with the methods or method families you plan to use.
4052 use CGI qw(-compile :standard :html3);
4056 use CGI qw(-compile :all);
4058 Note that using the -compile pragma in this way will always have
4059 the effect of importing the compiled functions into the current
4060 namespace. If you want to compile without importing use the
4061 compile() method instead (see below).
4065 This makes CGI.pm not generating the hidden fields .submit
4066 and .cgifields. It is very useful if you don't want to
4067 have the hidden fields appear in the querystring in a GET method.
4068 For example, a search script generated this way will have
4069 a very nice url with search parameters for bookmarking.
4071 =item -no_undef_params
4073 This keeps CGI.pm from including undef params in the parameter list.
4077 By default, CGI.pm versions 2.69 and higher emit XHTML
4078 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4079 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4084 This makes CGI.pm produce a header appropriate for an NPH (no
4085 parsed header) script. You may need to do other things as well
4086 to tell the server that the script is NPH. See the discussion
4087 of NPH scripts below.
4089 =item -newstyle_urls
4091 Separate the name=value pairs in CGI parameter query strings with
4092 semicolons rather than ampersands. For example:
4094 ?name=fred;age=24;favorite_color=3
4096 Semicolon-delimited query strings are always accepted, but will not be
4097 emitted by self_url() and query_string() unless the -newstyle_urls
4098 pragma is specified.
4100 This became the default in version 2.64.
4102 =item -oldstyle_urls
4104 Separate the name=value pairs in CGI parameter query strings with
4105 ampersands rather than semicolons. This is no longer the default.
4109 This overrides the autoloader so that any function in your program
4110 that is not recognized is referred to CGI.pm for possible evaluation.
4111 This allows you to use all the CGI.pm functions without adding them to
4112 your symbol table, which is of concern for mod_perl users who are
4113 worried about memory consumption. I<Warning:> when
4114 I<-autoload> is in effect, you cannot use "poetry mode"
4115 (functions without the parenthesis). Use I<hr()> rather
4116 than I<hr>, or add something like I<use subs qw/hr p header/>
4117 to the top of your script.
4121 This turns off the command-line processing features. If you want to
4122 run a CGI.pm script from the command line to produce HTML, and you
4123 don't want it to read CGI parameters from the command line or STDIN,
4124 then use this pragma:
4126 use CGI qw(-no_debug :standard);
4130 This turns on full debugging. In addition to reading CGI arguments
4131 from the command-line processing, CGI.pm will pause and try to read
4132 arguments from STDIN, producing the message "(offline mode: enter
4133 name=value pairs on standard input)" features.
4135 See the section on debugging for more details.
4137 =item -private_tempfiles
4139 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4140 file to a temporary directory, then deletes the file when done.
4141 However, this opens the risk of eavesdropping as described in the file
4142 upload section. Another CGI script author could peek at this data
4143 during the upload, even if it is confidential information. On Unix
4144 systems, the -private_tempfiles pragma will cause the temporary file
4145 to be unlinked as soon as it is opened and before any data is written
4146 into it, reducing, but not eliminating the risk of eavesdropping
4147 (there is still a potential race condition). To make life harder for
4148 the attacker, the program chooses tempfile names by calculating a 32
4149 bit checksum of the incoming HTTP headers.
4151 To ensure that the temporary file cannot be read by other CGI scripts,
4152 use suEXEC or a CGI wrapper program to run your script. The temporary
4153 file is created with mode 0600 (neither world nor group readable).
4155 The temporary directory is selected using the following algorithm:
4157 1. if the current user (e.g. "nobody") has a directory named
4158 "tmp" in its home directory, use that (Unix systems only).
4160 2. if the environment variable TMPDIR exists, use the location
4163 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4164 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4166 Each of these locations is checked that it is a directory and is
4167 writable. If not, the algorithm tries the next choice.
4171 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4173 Many of the methods generate HTML tags. As described below, tag
4174 functions automatically generate both the opening and closing tags.
4177 print h1('Level 1 Header');
4181 <H1>Level 1 Header</H1>
4183 There will be some times when you want to produce the start and end
4184 tags yourself. In this case, you can use the form start_I<tag_name>
4185 and end_I<tag_name>, as in:
4187 print start_h1,'Level 1 Header',end_h1;
4189 With a few exceptions (described below), start_I<tag_name> and
4190 end_I<tag_name> functions are not generated automatically when you
4191 I<use CGI>. However, you can specify the tags you want to generate
4192 I<start/end> functions for by putting an asterisk in front of their
4193 name, or, alternatively, requesting either "start_I<tag_name>" or
4194 "end_I<tag_name>" in the import list.
4198 use CGI qw/:standard *table start_ul/;
4200 In this example, the following functions are generated in addition to
4205 =item 1. start_table() (generates a <TABLE> tag)
4207 =item 2. end_table() (generates a </TABLE> tag)
4209 =item 3. start_ul() (generates a <UL> tag)
4211 =item 4. end_ul() (generates a </UL> tag)
4215 =head1 GENERATING DYNAMIC DOCUMENTS
4217 Most of CGI.pm's functions deal with creating documents on the fly.
4218 Generally you will produce the HTTP header first, followed by the
4219 document itself. CGI.pm provides functions for generating HTTP
4220 headers of various types as well as for generating HTML. For creating
4221 GIF images, see the GD.pm module.
4223 Each of these functions produces a fragment of HTML or HTTP which you
4224 can print out directly so that it displays in the browser window,
4225 append to a string, or save to a file for later use.
4227 =head2 CREATING A STANDARD HTTP HEADER:
4229 Normally the first thing you will do in any CGI script is print out an
4230 HTTP header. This tells the browser what type of document to expect,
4231 and gives other optional information, such as the language, expiration
4232 date, and whether to cache the document. The header can also be
4233 manipulated for special purposes, such as server push and pay per view
4236 print $query->header;
4240 print $query->header('image/gif');
4244 print $query->header('text/html','204 No response');
4248 print $query->header(-type=>'image/gif',
4250 -status=>'402 Payment required',
4254 -attachment=>'foo.gif',
4257 header() returns the Content-type: header. You can provide your own
4258 MIME type if you choose, otherwise it defaults to text/html. An
4259 optional second parameter specifies the status code and a human-readable
4260 message. For example, you can specify 204, "No response" to create a
4261 script that tells the browser to do nothing at all.
4263 The last example shows the named argument style for passing arguments
4264 to the CGI methods using named parameters. Recognized parameters are
4265 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
4266 parameters will be stripped of their initial hyphens and turned into
4267 header fields, allowing you to specify any HTTP header you desire.
4268 Internal underscores will be turned into hyphens:
4270 print $query->header(-Content_length=>3002);
4272 Most browsers will not cache the output from CGI scripts. Every time
4273 the browser reloads the page, the script is invoked anew. You can
4274 change this behavior with the B<-expires> parameter. When you specify
4275 an absolute or relative expiration interval with this parameter, some
4276 browsers and proxy servers will cache the script's output until the
4277 indicated expiration date. The following forms are all valid for the
4280 +30s 30 seconds from now
4281 +10m ten minutes from now
4282 +1h one hour from now
4283 -1d yesterday (i.e. "ASAP!")
4286 +10y in ten years time
4287 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
4289 The B<-cookie> parameter generates a header that tells the browser to provide
4290 a "magic cookie" during all subsequent transactions with your script.
4291 Netscape cookies have a special format that includes interesting attributes
4292 such as expiration time. Use the cookie() method to create and retrieve
4295 The B<-nph> parameter, if set to a true value, will issue the correct
4296 headers to work with a NPH (no-parse-header) script. This is important
4297 to use with certain servers that expect all their scripts to be NPH.
4299 The B<-charset> parameter can be used to control the character set
4300 sent to the browser. If not provided, defaults to ISO-8859-1. As a
4301 side effect, this sets the charset() method as well.
4303 The B<-attachment> parameter can be used to turn the page into an
4304 attachment. Instead of displaying the page, some browsers will prompt
4305 the user to save it to disk. The value of the argument is the
4306 suggested name for the saved file. In order for this to work, you may
4307 have to set the B<-type> to "application/octet-stream".
4309 =head2 GENERATING A REDIRECTION HEADER
4311 print $query->redirect('http://somewhere.else/in/movie/land');
4313 Sometimes you don't want to produce a document yourself, but simply
4314 redirect the browser elsewhere, perhaps choosing a URL based on the
4315 time of day or the identity of the user.
4317 The redirect() function redirects the browser to a different URL. If
4318 you use redirection like this, you should B<not> print out a header as
4321 One hint I can offer is that relative links may not work correctly
4322 when you generate a redirection to another document on your site.
4323 This is due to a well-intentioned optimization that some servers use.
4324 The solution to this is to use the full URL (including the http: part)
4325 of the document you are redirecting to.
4327 You can also use named arguments:
4329 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4332 The B<-nph> parameter, if set to a true value, will issue the correct
4333 headers to work with a NPH (no-parse-header) script. This is important
4334 to use with certain servers, such as Microsoft Internet Explorer, which
4335 expect all their scripts to be NPH.
4337 =head2 CREATING THE HTML DOCUMENT HEADER
4339 print $query->start_html(-title=>'Secrets of the Pyramids',
4340 -author=>'fred@capricorn.org',
4343 -meta=>{'keywords'=>'pharaoh secret mummy',
4344 'copyright'=>'copyright 1996 King Tut'},
4345 -style=>{'src'=>'/styles/style1.css'},
4348 After creating the HTTP header, most CGI scripts will start writing
4349 out an HTML document. The start_html() routine creates the top of the
4350 page, along with a lot of optional information that controls the
4351 page's appearance and behavior.
4353 This method returns a canned HTML header and the opening <BODY> tag.
4354 All parameters are optional. In the named parameter form, recognized
4355 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4356 (see below for the explanation). Any additional parameters you
4357 provide, such as the Netscape unofficial BGCOLOR attribute, are added
4358 to the <BODY> tag. Additional parameters must be proceeded by a
4361 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
4362 different from the current location, as in
4364 -xbase=>"http://home.mcom.com/"
4366 All relative links will be interpreted relative to this tag.
4368 The argument B<-target> allows you to provide a default target frame
4369 for all the links and fill-out forms on the page. B<This is a
4370 non-standard HTTP feature which only works with Netscape browsers!>
4371 See the Netscape documentation on frames for details of how to
4374 -target=>"answer_window"
4376 All relative links will be interpreted relative to this tag.
4377 You add arbitrary meta information to the header with the B<-meta>
4378 argument. This argument expects a reference to an associative array
4379 containing name/value pairs of meta information. These will be turned
4380 into a series of header <META> tags that look something like this:
4382 <META NAME="keywords" CONTENT="pharaoh secret mummy">
4383 <META NAME="description" CONTENT="copyright 1996 King Tut">
4385 To create an HTTP-EQUIV type of <META> tag, use B<-head>, described
4388 The B<-style> argument is used to incorporate cascading stylesheets
4389 into your code. See the section on CASCADING STYLESHEETS for more
4392 The B<-lang> argument is used to incorporate a language attribute into
4393 the <HTML> tag. The default if not specified is "en-US" for US
4394 English. For example:
4396 print $q->start_html(-lang=>'fr-CA');
4398 You can place other arbitrary HTML elements to the <HEAD> section with the
4399 B<-head> tag. For example, to place the rarely-used <LINK> element in the
4400 head section, use this:
4402 print start_html(-head=>Link({-rel=>'next',
4403 -href=>'http://www.capricorn.com/s2.html'}));
4405 To incorporate multiple HTML elements into the <HEAD> section, just pass an
4408 print start_html(-head=>[
4410 -href=>'http://www.capricorn.com/s2.html'}),
4411 Link({-rel=>'previous',
4412 -href=>'http://www.capricorn.com/s1.html'})
4416 And here's how to create an HTTP-EQUIV <META> tag:
4418 print start_html(-head=>meta({-http_equiv => 'Content-Type',
4419 -content => 'text/html'}))
4422 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4423 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4424 to add Netscape JavaScript calls to your pages. B<-script> should
4425 point to a block of text containing JavaScript function definitions.
4426 This block will be placed within a <SCRIPT> block inside the HTML (not
4427 HTTP) header. The block is placed in the header in order to give your
4428 page a fighting chance of having all its JavaScript functions in place
4429 even if the user presses the stop button before the page has loaded
4430 completely. CGI.pm attempts to format the script in such a way that
4431 JavaScript-naive browsers will not choke on the code: unfortunately
4432 there are some browsers, such as Chimera for Unix, that get confused
4435 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4436 code to execute when the page is respectively opened and closed by the
4437 browser. Usually these parameters are calls to functions defined in the
4441 print $query->header;
4443 // Ask a silly question
4444 function riddle_me_this() {
4445 var r = prompt("What walks on four legs in the morning, " +
4446 "two legs in the afternoon, " +
4447 "and three legs in the evening?");
4450 // Get a silly answer
4451 function response(answer) {
4452 if (answer == "man")
4453 alert("Right you are!");
4455 alert("Wrong! Guess again.");
4458 print $query->start_html(-title=>'The Riddle of the Sphinx',
4461 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4462 browsers that do not have JavaScript (or browsers where JavaScript is turned
4465 Netscape 3.0 recognizes several attributes of the <SCRIPT> tag,
4466 including LANGUAGE and SRC. The latter is particularly interesting,
4467 as it allows you to keep the JavaScript code in a file or CGI script
4468 rather than cluttering up each page with the source. To use these
4469 attributes pass a HASH reference in the B<-script> parameter containing
4470 one or more of -language, -src, or -code:
4472 print $q->start_html(-title=>'The Riddle of the Sphinx',
4473 -script=>{-language=>'JAVASCRIPT',
4474 -src=>'/javascript/sphinx.js'}
4477 print $q->(-title=>'The Riddle of the Sphinx',
4478 -script=>{-language=>'PERLSCRIPT',
4479 -code=>'print "hello world!\n;"'}
4483 A final feature allows you to incorporate multiple <SCRIPT> sections into the
4484 header. Just pass the list of script sections as an array reference.
4485 this allows you to specify different source files for different dialects
4486 of JavaScript. Example:
4488 print $q->start_html(-title=>'The Riddle of the Sphinx',
4490 { -language => 'JavaScript1.0',
4491 -src => '/javascript/utilities10.js'
4493 { -language => 'JavaScript1.1',
4494 -src => '/javascript/utilities11.js'
4496 { -language => 'JavaScript1.2',
4497 -src => '/javascript/utilities12.js'
4499 { -language => 'JavaScript28.2',
4500 -src => '/javascript/utilities219.js'
4506 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4510 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4512 for more information about JavaScript.
4514 The old-style positional parameters are as follows:
4518 =item B<Parameters:>
4526 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
4530 A 'true' flag if you want to include a <BASE> tag in the header. This
4531 helps resolve relative addresses to absolute ones when the document is moved,
4532 but makes the document hierarchy non-portable. Use with care!
4536 Any other parameters you want to include in the <BODY> tag. This is a good
4537 place to put Netscape extensions, such as colors and wallpaper patterns.
4541 =head2 ENDING THE HTML DOCUMENT:
4543 print $query->end_html
4545 This ends an HTML document by printing the </BODY></HTML> tags.
4547 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4549 $myself = $query->self_url;
4550 print q(<A HREF="$myself">I'm talking to myself.</A>);
4552 self_url() will return a URL, that, when selected, will reinvoke
4553 this script with all its state information intact. This is most
4554 useful when you want to jump around within the document using
4555 internal anchors but you don't want to disrupt the current contents
4556 of the form(s). Something like this will do the trick.
4558 $myself = $query->self_url;
4559 print "<A HREF=$myself#table1>See table 1</A>";
4560 print "<A HREF=$myself#table2>See table 2</A>";
4561 print "<A HREF=$myself#yourself>See for yourself</A>";
4563 If you want more control over what's returned, using the B<url()>
4566 You can also retrieve the unprocessed query string with query_string():
4568 $the_string = $query->query_string;
4570 =head2 OBTAINING THE SCRIPT'S URL
4572 $full_url = $query->url();
4573 $full_url = $query->url(-full=>1); #alternative syntax
4574 $relative_url = $query->url(-relative=>1);
4575 $absolute_url = $query->url(-absolute=>1);
4576 $url_with_path = $query->url(-path_info=>1);
4577 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4578 $netloc = $query->url(-base => 1);
4580 B<url()> returns the script's URL in a variety of formats. Called
4581 without any arguments, it returns the full form of the URL, including
4582 host name and port number
4584 http://your.host.com/path/to/script.cgi
4586 You can modify this format with the following named arguments:
4592 If true, produce an absolute URL, e.g.
4598 Produce a relative URL. This is useful if you want to reinvoke your
4599 script with different parameters. For example:
4605 Produce the full URL, exactly as if called without any arguments.
4606 This overrides the -relative and -absolute arguments.
4608 =item B<-path> (B<-path_info>)
4610 Append the additional path information to the URL. This can be
4611 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
4612 is provided as a synonym.
4614 =item B<-query> (B<-query_string>)
4616 Append the query string to the URL. This can be combined with
4617 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
4622 Generate just the protocol and net location, as in http://www.foo.com:8000
4626 =head2 MIXING POST AND URL PARAMETERS
4628 $color = $query->url_param('color');
4630 It is possible for a script to receive CGI parameters in the URL as
4631 well as in the fill-out form by creating a form that POSTs to a URL
4632 containing a query string (a "?" mark followed by arguments). The
4633 B<param()> method will always return the contents of the POSTed
4634 fill-out form, ignoring the URL's query string. To retrieve URL
4635 parameters, call the B<url_param()> method. Use it in the same way as
4636 B<param()>. The main difference is that it allows you to read the
4637 parameters, but not set them.
4640 Under no circumstances will the contents of the URL query string
4641 interfere with similarly-named CGI parameters in POSTed forms. If you
4642 try to mix a URL query string with a form submitted with the GET
4643 method, the results will not be what you expect.
4645 =head1 CREATING STANDARD HTML ELEMENTS:
4647 CGI.pm defines general HTML shortcut methods for most, if not all of
4648 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
4649 HTML element and return a fragment of HTML text that you can then
4650 print or manipulate as you like. Each shortcut returns a fragment of
4651 HTML code that you can append to a string, save to a file, or, most
4652 commonly, print out so that it displays in the browser window.
4654 This example shows how to use the HTML methods:
4657 print $q->blockquote(
4658 "Many years ago on the island of",
4659 $q->a({href=>"http://crete.org/"},"Crete"),
4660 "there lived a Minotaur named",
4661 $q->strong("Fred."),
4665 This results in the following HTML code (extra newlines have been
4666 added for readability):
4669 Many years ago on the island of
4670 <a HREF="http://crete.org/">Crete</a> there lived
4671 a minotaur named <strong>Fred.</strong>
4675 If you find the syntax for calling the HTML shortcuts awkward, you can
4676 import them into your namespace and dispense with the object syntax
4677 completely (see the next section for more details):
4679 use CGI ':standard';
4681 "Many years ago on the island of",
4682 a({href=>"http://crete.org/"},"Crete"),
4683 "there lived a minotaur named",
4688 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4690 The HTML methods will accept zero, one or multiple arguments. If you
4691 provide no arguments, you get a single tag:
4695 If you provide one or more string arguments, they are concatenated
4696 together with spaces and placed between opening and closing tags:
4698 print h1("Chapter","1"); # <H1>Chapter 1</H1>"
4700 If the first argument is an associative array reference, then the keys
4701 and values of the associative array become the HTML tag's attributes:
4703 print a({-href=>'fred.html',-target=>'_new'},
4704 "Open a new frame");
4706 <A HREF="fred.html",TARGET="_new">Open a new frame</A>
4708 You may dispense with the dashes in front of the attribute names if
4711 print img {src=>'fred.gif',align=>'LEFT'};
4713 <IMG ALIGN="LEFT" SRC="fred.gif">
4715 Sometimes an HTML tag attribute has no argument. For example, ordered
4716 lists can be marked as COMPACT. The syntax for this is an argument that
4717 that points to an undef string:
4719 print ol({compact=>undef},li('one'),li('two'),li('three'));
4721 Prior to CGI.pm version 2.41, providing an empty ('') string as an
4722 attribute argument was the same as providing undef. However, this has
4723 changed in order to accommodate those who want to create tags of the form
4724 <IMG ALT="">. The difference is shown in these two pieces of code:
4727 img({alt=>undef}) <IMG ALT>
4728 img({alt=>''}) <IMT ALT="">
4730 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
4732 One of the cool features of the HTML shortcuts is that they are
4733 distributive. If you give them an argument consisting of a
4734 B<reference> to a list, the tag will be distributed across each
4735 element of the list. For example, here's one way to make an ordered
4739 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
4742 This example will result in HTML output that looks like this:
4745 <LI TYPE="disc">Sneezy</LI>
4746 <LI TYPE="disc">Doc</LI>
4747 <LI TYPE="disc">Sleepy</LI>
4748 <LI TYPE="disc">Happy</LI>
4751 This is extremely useful for creating tables. For example:
4753 print table({-border=>undef},
4754 caption('When Should You Eat Your Vegetables?'),
4755 Tr({-align=>CENTER,-valign=>TOP},
4757 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
4758 td(['Tomatoes' , 'no', 'yes', 'yes']),
4759 td(['Broccoli' , 'no', 'no', 'yes']),
4760 td(['Onions' , 'yes','yes', 'yes'])
4765 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
4767 Consider this bit of code:
4769 print blockquote(em('Hi'),'mom!'));
4771 It will ordinarily return the string that you probably expect, namely:
4773 <BLOCKQUOTE><EM>Hi</EM> mom!</BLOCKQUOTE>
4775 Note the space between the element "Hi" and the element "mom!".
4776 CGI.pm puts the extra space there using array interpolation, which is
4777 controlled by the magic $" variable. Sometimes this extra space is
4778 not what you want, for example, when you are trying to align a series
4779 of images. In this case, you can simply change the value of $" to an
4784 print blockquote(em('Hi'),'mom!'));
4787 I suggest you put the code in a block as shown here. Otherwise the
4788 change to $" will affect all subsequent code until you explicitly
4791 =head2 NON-STANDARD HTML SHORTCUTS
4793 A few HTML tags don't follow the standard pattern for various
4796 B<comment()> generates an HTML comment (<!-- comment -->). Call it
4799 print comment('here is my comment');
4801 Because of conflicts with built-in Perl functions, the following functions
4802 begin with initial caps:
4811 In addition, start_html(), end_html(), start_form(), end_form(),
4812 start_multipart_form() and all the fill-out form tags are special.
4813 See their respective sections.
4815 =head2 AUTOESCAPING HTML
4817 By default, all HTML that is emitted by the form-generating functions
4818 is passed through a function called escapeHTML():
4822 =item $escaped_string = escapeHTML("unescaped string");
4824 Escape HTML formatting characters in a string.
4828 Provided that you have specified a character set of ISO-8859-1 (the
4829 default), the standard HTML escaping rules will be used. The "<"
4830 character becomes "<", ">" becomes ">", "&" becomes "&", and
4831 the quote character becomes """. In addition, the hexadecimal
4832 0x8b and 0x9b characters, which many windows-based browsers interpret
4833 as the left and right angle-bracket characters, are replaced by their
4834 numeric HTML entities ("‹" and "›"). If you manually change
4835 the charset, either by calling the charset() method explicitly or by
4836 passing a -charset argument to header(), then B<all> characters will
4837 be replaced by their numeric entities, since CGI.pm has no lookup
4838 table for all the possible encodings.
4840 The automatic escaping does not apply to other shortcuts, such as
4841 h1(). You should call escapeHTML() yourself on untrusted data in
4842 order to protect your pages against nasty tricks that people may enter
4843 into guestbooks, etc.. To change the character set, use charset().
4844 To turn autoescaping off completely, use autoescape():
4848 =item $charset = charset([$charset]);
4850 Get or set the current character set.
4852 =item $flag = autoEscape([$flag]);
4854 Get or set the value of the autoescape flag.
4858 =head2 PRETTY-PRINTING HTML
4860 By default, all the HTML produced by these functions comes out as one
4861 long line without carriage returns or indentation. This is yuck, but
4862 it does reduce the size of the documents by 10-20%. To get
4863 pretty-printed output, please use L<CGI::Pretty>, a subclass
4864 contributed by Brian Paulsen.
4866 =head1 CREATING FILL-OUT FORMS:
4868 I<General note> The various form-creating methods all return strings
4869 to the caller, containing the tag or tags that will create the requested
4870 form element. You are responsible for actually printing out these strings.
4871 It's set up this way so that you can place formatting tags
4872 around the form elements.
4874 I<Another note> The default values that you specify for the forms are only
4875 used the B<first> time the script is invoked (when there is no query
4876 string). On subsequent invocations of the script (when there is a query
4877 string), the former values are used even if they are blank.
4879 If you want to change the value of a field from its previous value, you have two
4882 (1) call the param() method to set it.
4884 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
4885 This forces the default value to be used, regardless of the previous value:
4887 print $query->textfield(-name=>'field_name',
4888 -default=>'starting value',
4893 I<Yet another note> By default, the text and labels of form elements are
4894 escaped according to HTML rules. This means that you can safely use
4895 "<CLICK ME>" as the label for a button. However, it also interferes with
4896 your ability to incorporate special HTML character sequences, such as Á,
4897 into your fields. If you wish to turn off automatic escaping, call the
4898 autoEscape() method with a false value immediately after creating the CGI object:
4901 $query->autoEscape(undef);
4903 =head2 CREATING AN ISINDEX TAG
4905 print $query->isindex(-action=>$action);
4909 print $query->isindex($action);
4911 Prints out an <ISINDEX> tag. Not very exciting. The parameter
4912 -action specifies the URL of the script to process the query. The
4913 default is to process the query with the current script.
4915 =head2 STARTING AND ENDING A FORM
4917 print $query->start_form(-method=>$method,
4919 -enctype=>$encoding);
4920 <... various form stuff ...>
4921 print $query->endform;
4925 print $query->start_form($method,$action,$encoding);
4926 <... various form stuff ...>
4927 print $query->endform;
4929 start_form() will return a <FORM> tag with the optional method,
4930 action and form encoding that you specify. The defaults are:
4934 enctype: application/x-www-form-urlencoded
4936 endform() returns the closing </FORM> tag.
4938 Start_form()'s enctype argument tells the browser how to package the various
4939 fields of the form before sending the form to the server. Two
4940 values are possible:
4942 B<Note:> This method was previously named startform(), and startform()
4943 is still recognized as an alias.
4947 =item B<application/x-www-form-urlencoded>
4949 This is the older type of encoding used by all browsers prior to
4950 Netscape 2.0. It is compatible with many CGI scripts and is
4951 suitable for short fields containing text data. For your
4952 convenience, CGI.pm stores the name of this encoding
4953 type in B<&CGI::URL_ENCODED>.
4955 =item B<multipart/form-data>
4957 This is the newer type of encoding introduced by Netscape 2.0.
4958 It is suitable for forms that contain very large fields or that
4959 are intended for transferring binary data. Most importantly,
4960 it enables the "file upload" feature of Netscape 2.0 forms. For
4961 your convenience, CGI.pm stores the name of this encoding type
4962 in B<&CGI::MULTIPART>
4964 Forms that use this type of encoding are not easily interpreted
4965 by CGI scripts unless they use CGI.pm or another library designed
4970 For compatibility, the start_form() method uses the older form of
4971 encoding by default. If you want to use the newer form of encoding
4972 by default, you can call B<start_multipart_form()> instead of
4975 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
4976 for use with JavaScript. The -name parameter gives the
4977 form a name so that it can be identified and manipulated by
4978 JavaScript functions. -onSubmit should point to a JavaScript
4979 function that will be executed just before the form is submitted to your
4980 server. You can use this opportunity to check the contents of the form
4981 for consistency and completeness. If you find something wrong, you
4982 can put up an alert box or maybe fix things up yourself. You can
4983 abort the submission by returning false from this function.
4985 Usually the bulk of JavaScript functions are defined in a <SCRIPT>
4986 block in the HTML header and -onSubmit points to one of these function
4987 call. See start_html() for details.
4989 =head2 CREATING A TEXT FIELD
4991 print $query->textfield(-name=>'field_name',
4992 -default=>'starting value',
4997 print $query->textfield('field_name','starting value',50,80);
4999 textfield() will return a text input field.
5007 The first parameter is the required name for the field (-name).
5011 The optional second parameter is the default starting value for the field
5012 contents (-default).
5016 The optional third parameter is the size of the field in
5021 The optional fourth parameter is the maximum number of characters the
5022 field will accept (-maxlength).
5026 As with all these methods, the field will be initialized with its
5027 previous contents from earlier invocations of the script.
5028 When the form is processed, the value of the text field can be
5031 $value = $query->param('foo');
5033 If you want to reset it from its initial value after the script has been
5034 called once, you can do so like this:
5036 $query->param('foo',"I'm taking over this value!");
5038 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
5039 value, you can force its current value by using the -override (alias -force)
5042 print $query->textfield(-name=>'field_name',
5043 -default=>'starting value',
5048 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
5049 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
5050 parameters to register JavaScript event handlers. The onChange
5051 handler will be called whenever the user changes the contents of the
5052 text field. You can do text validation if you like. onFocus and
5053 onBlur are called respectively when the insertion point moves into and
5054 out of the text field. onSelect is called when the user changes the
5055 portion of the text that is selected.
5057 =head2 CREATING A BIG TEXT FIELD
5059 print $query->textarea(-name=>'foo',
5060 -default=>'starting value',
5066 print $query->textarea('foo','starting value',10,50);
5068 textarea() is just like textfield, but it allows you to specify
5069 rows and columns for a multiline text entry box. You can provide
5070 a starting value for the field, which can be long and contain
5073 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
5074 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
5075 recognized. See textfield().
5077 =head2 CREATING A PASSWORD FIELD
5079 print $query->password_field(-name=>'secret',
5080 -value=>'starting value',
5085 print $query->password_field('secret','starting value',50,80);
5087 password_field() is identical to textfield(), except that its contents
5088 will be starred out on the web page.
5090 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5091 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5092 recognized. See textfield().
5094 =head2 CREATING A FILE UPLOAD FIELD
5096 print $query->filefield(-name=>'uploaded_file',
5097 -default=>'starting value',
5102 print $query->filefield('uploaded_file','starting value',50,80);
5104 filefield() will return a file upload field for Netscape 2.0 browsers.
5105 In order to take full advantage of this I<you must use the new
5106 multipart encoding scheme> for the form. You can do this either
5107 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5108 or by calling the new method B<start_multipart_form()> instead of
5109 vanilla B<start_form()>.
5117 The first parameter is the required name for the field (-name).
5121 The optional second parameter is the starting value for the field contents
5122 to be used as the default file name (-default).
5124 For security reasons, browsers don't pay any attention to this field,
5125 and so the starting value will always be blank. Worse, the field
5126 loses its "sticky" behavior and forgets its previous contents. The
5127 starting value field is called for in the HTML specification, however,
5128 and possibly some browser will eventually provide support for it.
5132 The optional third parameter is the size of the field in
5137 The optional fourth parameter is the maximum number of characters the
5138 field will accept (-maxlength).
5142 When the form is processed, you can retrieve the entered filename
5145 $filename = $query->param('uploaded_file');
5147 Different browsers will return slightly different things for the
5148 name. Some browsers return the filename only. Others return the full
5149 path to the file, using the path conventions of the user's machine.
5150 Regardless, the name returned is always the name of the file on the
5151 I<user's> machine, and is unrelated to the name of the temporary file
5152 that CGI.pm creates during upload spooling (see below).
5154 The filename returned is also a file handle. You can read the contents
5155 of the file using standard Perl file reading calls:
5157 # Read a text file and print it out
5158 while (<$filename>) {
5162 # Copy a binary file to somewhere safe
5163 open (OUTFILE,">>/usr/local/web/users/feedback");
5164 while ($bytesread=read($filename,$buffer,1024)) {
5165 print OUTFILE $buffer;
5168 However, there are problems with the dual nature of the upload fields.
5169 If you C<use strict>, then Perl will complain when you try to use a
5170 string as a filehandle. You can get around this by placing the file
5171 reading code in a block containing the C<no strict> pragma. More
5172 seriously, it is possible for the remote user to type garbage into the
5173 upload field, in which case what you get from param() is not a
5174 filehandle at all, but a string.
5176 To be safe, use the I<upload()> function (new in version 2.47). When
5177 called with the name of an upload field, I<upload()> returns a
5178 filehandle, or undef if the parameter is not a valid filehandle.
5180 $fh = $query->upload('uploaded_file');
5185 In an array context, upload() will return an array of filehandles.
5186 This makes it possible to create forms that use the same name for
5187 multiple upload fields.
5189 This is the recommended idiom.
5191 When a file is uploaded the browser usually sends along some
5192 information along with it in the format of headers. The information
5193 usually includes the MIME content type. Future browsers may send
5194 other information as well (such as modification date and size). To
5195 retrieve this information, call uploadInfo(). It returns a reference to
5196 an associative array containing all the document headers.
5198 $filename = $query->param('uploaded_file');
5199 $type = $query->uploadInfo($filename)->{'Content-Type'};
5200 unless ($type eq 'text/html') {
5201 die "HTML FILES ONLY!";
5204 If you are using a machine that recognizes "text" and "binary" data
5205 modes, be sure to understand when and how to use them (see the Camel book).
5206 Otherwise you may find that binary files are corrupted during file
5209 There are occasionally problems involving parsing the uploaded file.
5210 This usually happens when the user presses "Stop" before the upload is
5211 finished. In this case, CGI.pm will return undef for the name of the
5212 uploaded file and set I<cgi_error()> to the string "400 Bad request
5213 (malformed multipart POST)". This error message is designed so that
5214 you can incorporate it into a status code to be sent to the browser.
5217 $file = $query->upload('uploaded_file');
5218 if (!$file && $query->cgi_error) {
5219 print $query->header(-status=>$query->cgi_error);
5223 You are free to create a custom HTML page to complain about the error,
5226 If you are using CGI.pm on a Windows platform and find that binary
5227 files get slightly larger when uploaded but that text files remain the
5228 same, then you have forgotten to activate binary mode on the output
5229 filehandle. Be sure to call binmode() on any handle that you create
5230 to write the uploaded file to disk.
5232 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5233 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5234 recognized. See textfield() for details.
5236 =head2 CREATING A POPUP MENU
5238 print $query->popup_menu('menu_name',
5239 ['eenie','meenie','minie'],
5244 %labels = ('eenie'=>'your first choice',
5245 'meenie'=>'your second choice',
5246 'minie'=>'your third choice');
5247 print $query->popup_menu('menu_name',
5248 ['eenie','meenie','minie'],
5251 -or (named parameter style)-
5253 print $query->popup_menu(-name=>'menu_name',
5254 -values=>['eenie','meenie','minie'],
5258 popup_menu() creates a menu.
5264 The required first argument is the menu's name (-name).
5268 The required second argument (-values) is an array B<reference>
5269 containing the list of menu items in the menu. You can pass the
5270 method an anonymous array, as shown in the example, or a reference to
5271 a named array, such as "\@foo".
5275 The optional third parameter (-default) is the name of the default
5276 menu choice. If not specified, the first item will be the default.
5277 The values of the previous choice will be maintained across queries.
5281 The optional fourth parameter (-labels) is provided for people who
5282 want to use different values for the user-visible label inside the
5283 popup menu nd the value returned to your script. It's a pointer to an
5284 associative array relating menu values to user-visible labels. If you
5285 leave this parameter blank, the menu values will be displayed by
5286 default. (You can also leave a label undefined if you want to).
5290 When the form is processed, the selected value of the popup menu can
5293 $popup_menu_value = $query->param('menu_name');
5295 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
5296 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5297 B<-onBlur>. See the textfield() section for details on when these
5298 handlers are called.
5300 =head2 CREATING A SCROLLING LIST
5302 print $query->scrolling_list('list_name',
5303 ['eenie','meenie','minie','moe'],
5304 ['eenie','moe'],5,'true');
5307 print $query->scrolling_list('list_name',
5308 ['eenie','meenie','minie','moe'],
5309 ['eenie','moe'],5,'true',
5314 print $query->scrolling_list(-name=>'list_name',
5315 -values=>['eenie','meenie','minie','moe'],
5316 -default=>['eenie','moe'],
5321 scrolling_list() creates a scrolling list.
5325 =item B<Parameters:>
5329 The first and second arguments are the list name (-name) and values
5330 (-values). As in the popup menu, the second argument should be an
5335 The optional third argument (-default) can be either a reference to a
5336 list containing the values to be selected by default, or can be a
5337 single value to select. If this argument is missing or undefined,
5338 then nothing is selected when the list first appears. In the named
5339 parameter version, you can use the synonym "-defaults" for this
5344 The optional fourth argument is the size of the list (-size).
5348 The optional fifth argument can be set to true to allow multiple
5349 simultaneous selections (-multiple). Otherwise only one selection
5350 will be allowed at a time.
5354 The optional sixth argument is a pointer to an associative array
5355 containing long user-visible labels for the list items (-labels).
5356 If not provided, the values will be displayed.
5358 When this form is processed, all selected list items will be returned as
5359 a list under the parameter name 'list_name'. The values of the
5360 selected items can be retrieved with:
5362 @selected = $query->param('list_name');
5366 JAVASCRIPTING: scrolling_list() recognizes the following event
5367 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5368 and B<-onBlur>. See textfield() for the description of when these
5369 handlers are called.
5371 =head2 CREATING A GROUP OF RELATED CHECKBOXES
5373 print $query->checkbox_group(-name=>'group_name',
5374 -values=>['eenie','meenie','minie','moe'],
5375 -default=>['eenie','moe'],
5379 print $query->checkbox_group('group_name',
5380 ['eenie','meenie','minie','moe'],
5381 ['eenie','moe'],'true',\%labels);
5383 HTML3-COMPATIBLE BROWSERS ONLY:
5385 print $query->checkbox_group(-name=>'group_name',
5386 -values=>['eenie','meenie','minie','moe'],
5387 -rows=2,-columns=>2);
5390 checkbox_group() creates a list of checkboxes that are related
5395 =item B<Parameters:>
5399 The first and second arguments are the checkbox name and values,
5400 respectively (-name and -values). As in the popup menu, the second
5401 argument should be an array reference. These values are used for the
5402 user-readable labels printed next to the checkboxes as well as for the
5403 values passed to your script in the query string.
5407 The optional third argument (-default) can be either a reference to a
5408 list containing the values to be checked by default, or can be a
5409 single value to checked. If this argument is missing or undefined,
5410 then nothing is selected when the list first appears.
5414 The optional fourth argument (-linebreak) can be set to true to place
5415 line breaks between the checkboxes so that they appear as a vertical
5416 list. Otherwise, they will be strung together on a horizontal line.
5420 The optional fifth argument is a pointer to an associative array
5421 relating the checkbox values to the user-visible labels that will
5422 be printed next to them (-labels). If not provided, the values will
5423 be used as the default.
5427 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5428 the optional parameters B<-rows>, and B<-columns>. These parameters
5429 cause checkbox_group() to return an HTML3 compatible table containing
5430 the checkbox group formatted with the specified number of rows and
5431 columns. You can provide just the -columns parameter if you wish;
5432 checkbox_group will calculate the correct number of rows for you.
5434 To include row and column headings in the returned table, you
5435 can use the B<-rowheaders> and B<-colheaders> 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 checkboxes -- they're still a single named
5443 When the form is processed, all checked boxes will be returned as
5444 a list under the parameter name 'group_name'. The values of the
5445 "on" checkboxes can be retrieved with:
5447 @turned_on = $query->param('group_name');
5449 The value returned by checkbox_group() is actually an array of button
5450 elements. You can capture them and use them within tables, lists,
5451 or in other creative ways:
5453 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
5454 &use_in_creative_way(@h);
5456 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
5457 parameter. This specifies a JavaScript code fragment or
5458 function call to be executed every time the user clicks on
5459 any of the buttons in the group. You can retrieve the identity
5460 of the particular button clicked on using the "this" variable.
5462 =head2 CREATING A STANDALONE CHECKBOX
5464 print $query->checkbox(-name=>'checkbox_name',
5465 -checked=>'checked',
5467 -label=>'CLICK ME');
5471 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
5473 checkbox() is used to create an isolated checkbox that isn't logically
5474 related to any others.
5478 =item B<Parameters:>
5482 The first parameter is the required name for the checkbox (-name). It
5483 will also be used for the user-readable label printed next to the
5488 The optional second parameter (-checked) specifies that the checkbox
5489 is turned on by default. Synonyms are -selected and -on.
5493 The optional third parameter (-value) specifies the value of the
5494 checkbox when it is checked. If not provided, the word "on" is
5499 The optional fourth parameter (-label) is the user-readable label to
5500 be attached to the checkbox. If not provided, the checkbox name is
5505 The value of the checkbox can be retrieved using:
5507 $turned_on = $query->param('checkbox_name');
5509 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
5510 parameter. See checkbox_group() for further details.
5512 =head2 CREATING A RADIO BUTTON GROUP
5514 print $query->radio_group(-name=>'group_name',
5515 -values=>['eenie','meenie','minie'],
5522 print $query->radio_group('group_name',['eenie','meenie','minie'],
5523 'meenie','true',\%labels);
5526 HTML3-COMPATIBLE BROWSERS ONLY:
5528 print $query->radio_group(-name=>'group_name',
5529 -values=>['eenie','meenie','minie','moe'],
5530 -rows=2,-columns=>2);
5532 radio_group() creates a set of logically-related radio buttons
5533 (turning one member of the group on turns the others off)
5537 =item B<Parameters:>
5541 The first argument is the name of the group and is required (-name).
5545 The second argument (-values) is the list of values for the radio
5546 buttons. The values and the labels that appear on the page are
5547 identical. Pass an array I<reference> in the second argument, either
5548 using an anonymous array, as shown, or by referencing a named array as
5553 The optional third parameter (-default) is the name of the default
5554 button to turn on. If not specified, the first item will be the
5555 default. You can provide a nonexistent button name, such as "-" to
5556 start up with no buttons selected.
5560 The optional fourth parameter (-linebreak) can be set to 'true' to put
5561 line breaks between the buttons, creating a vertical list.
5565 The optional fifth parameter (-labels) is a pointer to an associative
5566 array relating the radio button values to user-visible labels to be
5567 used in the display. If not provided, the values themselves are
5572 B<HTML3-compatible browsers> (such as Netscape) can take advantage
5574 parameters B<-rows>, and B<-columns>. These parameters cause
5575 radio_group() to return an HTML3 compatible table containing
5576 the radio group formatted with the specified number of rows
5577 and columns. You can provide just the -columns parameter if you
5578 wish; radio_group will calculate the correct number of rows
5581 To include row and column headings in the returned table, you
5582 can use the B<-rowheader> and B<-colheader> parameters. Both
5583 of these accept a pointer to an array of headings to use.
5584 The headings are just decorative. They don't reorganize the
5585 interpretation of the radio buttons -- they're still a single named
5590 When the form is processed, the selected radio button can
5593 $which_radio_button = $query->param('group_name');
5595 The value returned by radio_group() is actually an array of button
5596 elements. You can capture them and use them within tables, lists,
5597 or in other creative ways:
5599 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
5600 &use_in_creative_way(@h);
5602 =head2 CREATING A SUBMIT BUTTON
5604 print $query->submit(-name=>'button_name',
5609 print $query->submit('button_name','value');
5611 submit() will create the query submission button. Every form
5612 should have one of these.
5616 =item B<Parameters:>
5620 The first argument (-name) is optional. You can give the button a
5621 name if you have several submission buttons in your form and you want
5622 to distinguish between them. The name will also be used as the
5623 user-visible label. Be aware that a few older browsers don't deal with this correctly and
5624 B<never> send back a value from a button.
5628 The second argument (-value) is also optional. This gives the button
5629 a value that will be passed to your script in the query string.
5633 You can figure out which button was pressed by using different
5634 values for each one:
5636 $which_one = $query->param('button_name');
5638 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
5639 parameter. See checkbox_group() for further details.
5641 =head2 CREATING A RESET BUTTON
5645 reset() creates the "reset" button. Note that it restores the
5646 form to its value from the last time the script was called,
5647 NOT necessarily to the defaults.
5649 Note that this conflicts with the Perl reset() built-in. Use
5650 CORE::reset() to get the original reset function.
5652 =head2 CREATING A DEFAULT BUTTON
5654 print $query->defaults('button_label')
5656 defaults() creates a button that, when invoked, will cause the
5657 form to be completely reset to its defaults, wiping out all the
5658 changes the user ever made.
5660 =head2 CREATING A HIDDEN FIELD
5662 print $query->hidden(-name=>'hidden_name',
5663 -default=>['value1','value2'...]);
5667 print $query->hidden('hidden_name','value1','value2'...);
5669 hidden() produces a text field that can't be seen by the user. It
5670 is useful for passing state variable information from one invocation
5671 of the script to the next.
5675 =item B<Parameters:>
5679 The first argument is required and specifies the name of this
5684 The second argument is also required and specifies its value
5685 (-default). In the named parameter style of calling, you can provide
5686 a single value here or a reference to a whole list
5690 Fetch the value of a hidden field this way:
5692 $hidden_value = $query->param('hidden_name');
5694 Note, that just like all the other form elements, the value of a
5695 hidden field is "sticky". If you want to replace a hidden field with
5696 some other values after the script has been called once you'll have to
5699 $query->param('hidden_name','new','values','here');
5701 =head2 CREATING A CLICKABLE IMAGE BUTTON
5703 print $query->image_button(-name=>'button_name',
5704 -src=>'/source/URL',
5709 print $query->image_button('button_name','/source/URL','MIDDLE');
5711 image_button() produces a clickable image. When it's clicked on the
5712 position of the click is returned to your script as "button_name.x"
5713 and "button_name.y", where "button_name" is the name you've assigned
5716 JAVASCRIPTING: image_button() recognizes the B<-onClick>
5717 parameter. See checkbox_group() for further details.
5721 =item B<Parameters:>
5725 The first argument (-name) is required and specifies the name of this
5730 The second argument (-src) is also required and specifies the URL
5734 The third option (-align, optional) is an alignment type, and may be
5735 TOP, BOTTOM or MIDDLE
5739 Fetch the value of the button this way:
5740 $x = $query->param('button_name.x');
5741 $y = $query->param('button_name.y');
5743 =head2 CREATING A JAVASCRIPT ACTION BUTTON
5745 print $query->button(-name=>'button_name',
5746 -value=>'user visible label',
5747 -onClick=>"do_something()");
5751 print $query->button('button_name',"do_something()");
5753 button() produces a button that is compatible with Netscape 2.0's
5754 JavaScript. When it's pressed the fragment of JavaScript code
5755 pointed to by the B<-onClick> parameter will be executed. On
5756 non-Netscape browsers this form element will probably not even
5761 Netscape browsers versions 1.1 and higher, and all versions of
5762 Internet Explorer, support a so-called "cookie" designed to help
5763 maintain state within a browser session. CGI.pm has several methods
5764 that support cookies.
5766 A cookie is a name=value pair much like the named parameters in a CGI
5767 query string. CGI scripts create one or more cookies and send
5768 them to the browser in the HTTP header. The browser maintains a list
5769 of cookies that belong to a particular Web server, and returns them
5770 to the CGI script during subsequent interactions.
5772 In addition to the required name=value pair, each cookie has several
5773 optional attributes:
5777 =item 1. an expiration time
5779 This is a time/date string (in a special GMT format) that indicates
5780 when a cookie expires. The cookie will be saved and returned to your
5781 script until this expiration date is reached if the user exits
5782 the browser and restarts it. If an expiration date isn't specified, the cookie
5783 will remain active until the user quits the browser.
5787 This is a partial or complete domain name for which the cookie is
5788 valid. The browser will return the cookie to any host that matches
5789 the partial domain name. For example, if you specify a domain name
5790 of ".capricorn.com", then the browser will return the cookie to
5791 Web servers running on any of the machines "www.capricorn.com",
5792 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
5793 must contain at least two periods to prevent attempts to match
5794 on top level domains like ".edu". If no domain is specified, then
5795 the browser will only return the cookie to servers on the host the
5796 cookie originated from.
5800 If you provide a cookie path attribute, the browser will check it
5801 against your script's URL before returning the cookie. For example,
5802 if you specify the path "/cgi-bin", then the cookie will be returned
5803 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
5804 and "/cgi-bin/customer_service/complain.pl", but not to the script
5805 "/cgi-private/site_admin.pl". By default, path is set to "/", which
5806 causes the cookie to be sent to any CGI script on your site.
5808 =item 4. a "secure" flag
5810 If the "secure" attribute is set, the cookie will only be sent to your
5811 script if the CGI request is occurring on a secure channel, such as SSL.
5815 The interface to HTTP cookies is the B<cookie()> method:
5817 $cookie = $query->cookie(-name=>'sessionID',
5820 -path=>'/cgi-bin/database',
5821 -domain=>'.capricorn.org',
5823 print $query->header(-cookie=>$cookie);
5825 B<cookie()> creates a new cookie. Its parameters include:
5831 The name of the cookie (required). This can be any string at all.
5832 Although browsers limit their cookie names to non-whitespace
5833 alphanumeric characters, CGI.pm removes this restriction by escaping
5834 and unescaping cookies behind the scenes.
5838 The value of the cookie. This can be any scalar value,
5839 array reference, or even associative array reference. For example,
5840 you can store an entire associative array into a cookie this way:
5842 $cookie=$query->cookie(-name=>'family information',
5843 -value=>\%childrens_ages);
5847 The optional partial path for which this cookie will be valid, as described
5852 The optional partial domain for which this cookie will be valid, as described
5857 The optional expiration date for this cookie. The format is as described
5858 in the section on the B<header()> method:
5860 "+1h" one hour from now
5864 If set to true, this cookie will only be used within a secure
5869 The cookie created by cookie() must be incorporated into the HTTP
5870 header within the string returned by the header() method:
5872 print $query->header(-cookie=>$my_cookie);
5874 To create multiple cookies, give header() an array reference:
5876 $cookie1 = $query->cookie(-name=>'riddle_name',
5877 -value=>"The Sphynx's Question");
5878 $cookie2 = $query->cookie(-name=>'answers',
5880 print $query->header(-cookie=>[$cookie1,$cookie2]);
5882 To retrieve a cookie, request it by name by calling cookie() method
5883 without the B<-value> parameter:
5887 $riddle = $query->cookie('riddle_name');
5888 %answers = $query->cookie('answers');
5890 Cookies created with a single scalar value, such as the "riddle_name"
5891 cookie, will be returned in that form. Cookies with array and hash
5892 values can also be retrieved.
5894 The cookie and CGI namespaces are separate. If you have a parameter
5895 named 'answers' and a cookie named 'answers', the values retrieved by
5896 param() and cookie() are independent of each other. However, it's
5897 simple to turn a CGI parameter into a cookie, and vice-versa:
5899 # turn a CGI parameter into a cookie
5900 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
5902 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
5904 See the B<cookie.cgi> example script for some ideas on how to use
5905 cookies effectively.
5907 =head1 WORKING WITH FRAMES
5909 It's possible for CGI.pm scripts to write into several browser panels
5910 and windows using the HTML 4 frame mechanism. There are three
5911 techniques for defining new frames programmatically:
5915 =item 1. Create a <Frameset> document
5917 After writing out the HTTP header, instead of creating a standard
5918 HTML document using the start_html() call, create a <FRAMESET>
5919 document that defines the frames on the page. Specify your script(s)
5920 (with appropriate parameters) as the SRC for each of the frames.
5922 There is no specific support for creating <FRAMESET> sections
5923 in CGI.pm, but the HTML is very simple to write. See the frame
5924 documentation in Netscape's home pages for details
5926 http://home.netscape.com/assist/net_sites/frames.html
5928 =item 2. Specify the destination for the document in the HTTP header
5930 You may provide a B<-target> parameter to the header() method:
5932 print $q->header(-target=>'ResultsWindow');
5934 This will tell the browser to load the output of your script into the
5935 frame named "ResultsWindow". If a frame of that name doesn't already
5936 exist, the browser will pop up a new window and load your script's
5937 document into that. There are a number of magic names that you can
5938 use for targets. See the frame documents on Netscape's home pages for
5941 =item 3. Specify the destination for the document in the <FORM> tag
5943 You can specify the frame to load in the FORM tag itself. With
5944 CGI.pm it looks like this:
5946 print $q->start_form(-target=>'ResultsWindow');
5948 When your script is reinvoked by the form, its output will be loaded
5949 into the frame named "ResultsWindow". If one doesn't already exist
5950 a new window will be created.
5954 The script "frameset.cgi" in the examples directory shows one way to
5955 create pages in which the fill-out form and the response live in
5956 side-by-side frames.
5958 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
5960 CGI.pm has limited support for HTML3's cascading style sheets (css).
5961 To incorporate a stylesheet into your document, pass the
5962 start_html() method a B<-style> parameter. The value of this
5963 parameter may be a scalar, in which case it is incorporated directly
5964 into a <STYLE> section, or it may be a hash reference. In the latter
5965 case you should provide the hash with one or more of B<-src> or
5966 B<-code>. B<-src> points to a URL where an externally-defined
5967 stylesheet can be found. B<-code> points to a scalar value to be
5968 incorporated into a <STYLE> section. Style definitions in B<-code>
5969 override similarly-named ones in B<-src>, hence the name "cascading."
5971 You may also specify the type of the stylesheet by adding the optional
5972 B<-type> parameter to the hash pointed to by B<-style>. If not
5973 specified, the style defaults to 'text/css'.
5975 To refer to a style within the body of your document, add the
5976 B<-class> parameter to any HTML element:
5978 print h1({-class=>'Fancy'},'Welcome to the Party');
5980 Or define styles on the fly with the B<-style> parameter:
5982 print h1({-style=>'Color: red;'},'Welcome to Hell');
5984 You may also use the new B<span()> element to apply a style to a
5987 print span({-style=>'Color: red;'},
5988 h1('Welcome to Hell'),
5989 "Where did that handbasket get to?"
5992 Note that you must import the ":html3" definitions to have the
5993 B<span()> method available. Here's a quick and dirty example of using
5994 CSS's. See the CSS specification at
5995 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
5997 use CGI qw/:standard :html3/;
5999 #here's a stylesheet incorporated directly into the page
6009 font-family: sans-serif;
6015 print start_html( -title=>'CGI with Style',
6016 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
6019 print h1('CGI with Style'),
6021 "Better read the cascading style sheet spec before playing with this!"),
6022 span({-style=>'color: magenta'},
6023 "Look Mom, no hands!",
6029 Pass an array reference to B<-style> in order to incorporate multiple
6030 stylesheets into your document.
6034 If you are running the script from the command line or in the perl
6035 debugger, you can pass the script a list of keywords or
6036 parameter=value pairs on the command line or from standard input (you
6037 don't have to worry about tricking your script into reading from
6038 environment variables). You can pass keywords like this:
6040 your_script.pl keyword1 keyword2 keyword3
6044 your_script.pl keyword1+keyword2+keyword3
6048 your_script.pl name1=value1 name2=value2
6052 your_script.pl name1=value1&name2=value2
6054 To turn off this feature, use the -no_debug pragma.
6056 To test the POST method, you may enable full debugging with the -debug
6057 pragma. This will allow you to feed newline-delimited name=value
6058 pairs to the script on standard input.
6060 When debugging, you can use quotes and backslashes to escape
6061 characters in the familiar shell manner, letting you place
6062 spaces and other funny characters in your parameter=value
6065 your_script.pl "name1='I am a long value'" "name2=two\ words"
6067 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
6069 The Dump() method produces a string consisting of all the query's
6070 name/value pairs formatted nicely as a nested list. This is useful
6071 for debugging purposes:
6076 Produces something that looks like:
6090 As a shortcut, you can interpolate the entire CGI object into a string
6091 and it will be replaced with the a nice HTML dump shown above:
6094 print "<H2>Current Values</H2> $query\n";
6096 =head1 FETCHING ENVIRONMENT VARIABLES
6098 Some of the more useful environment variables can be fetched
6099 through this interface. The methods are as follows:
6105 Return a list of MIME types that the remote browser accepts. If you
6106 give this method a single argument corresponding to a MIME type, as in
6107 $query->Accept('text/html'), it will return a floating point value
6108 corresponding to the browser's preference for this type from 0.0
6109 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
6110 list are handled correctly.
6112 Note that the capitalization changed between version 2.43 and 2.44 in
6113 order to avoid conflict with Perl's accept() function.
6115 =item B<raw_cookie()>
6117 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
6118 Netscape browsers version 1.1 and higher, and all versions of Internet
6119 Explorer. Cookies have a special format, and this method call just
6120 returns the raw form (?cookie dough). See cookie() for ways of
6121 setting and retrieving cooked cookies.
6123 Called with no parameters, raw_cookie() returns the packed cookie
6124 structure. You can separate it into individual cookies by splitting
6125 on the character sequence "; ". Called with the name of a cookie,
6126 retrieves the B<unescaped> form of the cookie. You can use the
6127 regular cookie() method to get the names, or use the raw_fetch()
6128 method from the CGI::Cookie module.
6130 =item B<user_agent()>
6132 Returns the HTTP_USER_AGENT variable. If you give
6133 this method a single argument, it will attempt to
6134 pattern match on it, allowing you to do something
6135 like $query->user_agent(netscape);
6137 =item B<path_info()>
6139 Returns additional path information from the script URL.
6140 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
6141 $query->path_info() returning "/additional/stuff".
6143 NOTE: The Microsoft Internet Information Server
6144 is broken with respect to additional path information. If
6145 you use the Perl DLL library, the IIS server will attempt to
6146 execute the additional path information as a Perl script.
6147 If you use the ordinary file associations mapping, the
6148 path information will be present in the environment,
6149 but incorrect. The best thing to do is to avoid using additional
6150 path information in CGI scripts destined for use with IIS.
6152 =item B<path_translated()>
6154 As per path_info() but returns the additional
6155 path information translated into a physical path, e.g.
6156 "/usr/local/etc/httpd/htdocs/additional/stuff".
6158 The Microsoft IIS is broken with respect to the translated
6161 =item B<remote_host()>
6163 Returns either the remote host name or IP address.
6164 if the former is unavailable.
6166 =item B<script_name()>
6168 Return the script name as a partial URL, for self-refering
6173 Return the URL of the page the browser was viewing
6174 prior to fetching your script. Not available for all
6177 =item B<auth_type ()>
6179 Return the authorization/verification method in use for this
6182 =item B<server_name ()>
6184 Returns the name of the server, usually the machine's host
6187 =item B<virtual_host ()>
6189 When using virtual hosts, returns the name of the host that
6190 the browser attempted to contact
6192 =item B<server_port ()>
6194 Return the port that the server is listening on.
6196 =item B<server_software ()>
6198 Returns the server software and version number.
6200 =item B<remote_user ()>
6202 Return the authorization/verification name used for user
6203 verification, if this script is protected.
6205 =item B<user_name ()>
6207 Attempt to obtain the remote user's name, using a variety of different
6208 techniques. This only works with older browsers such as Mosaic.
6209 Newer browsers do not report the user name for privacy reasons!
6211 =item B<request_method()>
6213 Returns the method used to access your script, usually
6214 one of 'POST', 'GET' or 'HEAD'.
6216 =item B<content_type()>
6218 Returns the content_type of data submitted in a POST, generally
6219 multipart/form-data or application/x-www-form-urlencoded
6223 Called with no arguments returns the list of HTTP environment
6224 variables, including such things as HTTP_USER_AGENT,
6225 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6226 like-named HTTP header fields in the request. Called with the name of
6227 an HTTP header field, returns its value. Capitalization and the use
6228 of hyphens versus underscores are not significant.
6230 For example, all three of these examples are equivalent:
6232 $requested_language = $q->http('Accept-language');
6233 $requested_language = $q->http('Accept_language');
6234 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6238 The same as I<http()>, but operates on the HTTPS environment variables
6239 present when the SSL protocol is in effect. Can be used to determine
6240 whether SSL is turned on.
6244 =head1 USING NPH SCRIPTS
6246 NPH, or "no-parsed-header", scripts bypass the server completely by
6247 sending the complete HTTP header directly to the browser. This has
6248 slight performance benefits, but is of most use for taking advantage
6249 of HTTP extensions that are not directly supported by your server,
6250 such as server push and PICS headers.
6252 Servers use a variety of conventions for designating CGI scripts as
6253 NPH. Many Unix servers look at the beginning of the script's name for
6254 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
6255 Internet Information Server, in contrast, try to decide whether a
6256 program is an NPH script by examining the first line of script output.
6259 CGI.pm supports NPH scripts with a special NPH mode. When in this
6260 mode, CGI.pm will output the necessary extra header information when
6261 the header() and redirect() methods are
6264 The Microsoft Internet Information Server requires NPH mode. As of version
6265 2.30, CGI.pm will automatically detect when the script is running under IIS
6266 and put itself into this mode. You do not need to do this manually, although
6267 it won't hurt anything if you do.
6269 There are a number of ways to put CGI.pm into NPH mode:
6273 =item In the B<use> statement
6275 Simply add the "-nph" pragmato the list of symbols to be imported into
6278 use CGI qw(:standard -nph)
6280 =item By calling the B<nph()> method:
6282 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
6286 =item By using B<-nph> parameters
6288 in the B<header()> and B<redirect()> statements:
6290 print $q->header(-nph=>1);
6296 CGI.pm provides four simple functions for producing multipart
6297 documents of the type needed to implement server push. These
6298 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
6299 import these into your namespace, you must import the ":push" set.
6300 You are also advised to put the script into NPH mode and to set $| to
6301 1 to avoid buffering problems.
6303 Here is a simple script that demonstrates server push:
6305 #!/usr/local/bin/perl
6306 use CGI qw/:push -nph/;
6308 print multipart_init(-boundary=>'----here we go!');
6310 print multipart_start(-type=>'text/plain'),
6311 "The current time is ",scalar(localtime),"\n";
6313 print multipart_end;
6315 print multipart_final;
6320 This script initializes server push by calling B<multipart_init()>.
6321 It then enters a loop in which it begins a new multipart section by
6322 calling B<multipart_start()>, prints the current local time,
6323 and ends a multipart section with B<multipart_end()>. It then sleeps
6324 a second, and begins again. On the final iteration, it ends the
6325 multipart section with B<multipart_final()> rather than with
6330 =item multipart_init()
6332 multipart_init(-boundary=>$boundary);
6334 Initialize the multipart system. The -boundary argument specifies
6335 what MIME boundary string to use to separate parts of the document.
6336 If not provided, CGI.pm chooses a reasonable boundary for you.
6338 =item multipart_start()
6340 multipart_start(-type=>$type)
6342 Start a new part of the multipart document using the specified MIME
6343 type. If not specified, text/html is assumed.
6345 =item multipart_end()
6349 End a part. You must remember to call multipart_end() once for each
6350 multipart_start(), except at the end of the last part of the multipart
6351 document when multipart_final() should be called instead of multipart_end().
6353 =item multipart_final()
6357 End all parts. You should call multipart_final() rather than
6358 multipart_end() at the end of the last part of the multipart document.
6362 Users interested in server push applications should also have a look
6363 at the CGI::Push module.
6365 Only Netscape Navigator supports server push. Internet Explorer
6368 =head1 Avoiding Denial of Service Attacks
6370 A potential problem with CGI.pm is that, by default, it attempts to
6371 process form POSTings no matter how large they are. A wily hacker
6372 could attack your site by sending a CGI script a huge POST of many
6373 megabytes. CGI.pm will attempt to read the entire POST into a
6374 variable, growing hugely in size until it runs out of memory. While
6375 the script attempts to allocate the memory the system may slow down
6376 dramatically. This is a form of denial of service attack.
6378 Another possible attack is for the remote user to force CGI.pm to
6379 accept a huge file upload. CGI.pm will accept the upload and store it
6380 in a temporary directory even if your script doesn't expect to receive
6381 an uploaded file. CGI.pm will delete the file automatically when it
6382 terminates, but in the meantime the remote user may have filled up the
6383 server's disk space, causing problems for other programs.
6385 The best way to avoid denial of service attacks is to limit the amount
6386 of memory, CPU time and disk space that CGI scripts can use. Some Web
6387 servers come with built-in facilities to accomplish this. In other
6388 cases, you can use the shell I<limit> or I<ulimit>
6389 commands to put ceilings on CGI resource usage.
6392 CGI.pm also has some simple built-in protections against denial of
6393 service attacks, but you must activate them before you can use them.
6394 These take the form of two global variables in the CGI name space:
6398 =item B<$CGI::POST_MAX>
6400 If set to a non-negative integer, this variable puts a ceiling
6401 on the size of POSTings, in bytes. If CGI.pm detects a POST
6402 that is greater than the ceiling, it will immediately exit with an error
6403 message. This value will affect both ordinary POSTs and
6404 multipart POSTs, meaning that it limits the maximum size of file
6405 uploads as well. You should set this to a reasonably high
6406 value, such as 1 megabyte.
6408 =item B<$CGI::DISABLE_UPLOADS>
6410 If set to a non-zero value, this will disable file uploads
6411 completely. Other fill-out form values will work as usual.
6415 You can use these variables in either of two ways.
6419 =item B<1. On a script-by-script basis>
6421 Set the variable at the top of the script, right after the "use" statement:
6423 use CGI qw/:standard/;
6424 use CGI::Carp 'fatalsToBrowser';
6425 $CGI::POST_MAX=1024 * 100; # max 100K posts
6426 $CGI::DISABLE_UPLOADS = 1; # no uploads
6428 =item B<2. Globally for all scripts>
6430 Open up CGI.pm, find the definitions for $POST_MAX and
6431 $DISABLE_UPLOADS, and set them to the desired values. You'll
6432 find them towards the top of the file in a subroutine named
6433 initialize_globals().
6437 An attempt to send a POST larger than $POST_MAX bytes will cause
6438 I<param()> to return an empty CGI parameter list. You can test for
6439 this event by checking I<cgi_error()>, either after you create the CGI
6440 object or, if you are using the function-oriented interface, call
6441 <param()> for the first time. If the POST was intercepted, then
6442 cgi_error() will return the message "413 POST too large".
6444 This error message is actually defined by the HTTP protocol, and is
6445 designed to be returned to the browser as the CGI script's status
6448 $uploaded_file = param('upload');
6449 if (!$uploaded_file && cgi_error()) {
6450 print header(-status=>cgi_error());
6454 However it isn't clear that any browser currently knows what to do
6455 with this status code. It might be better just to create an
6456 HTML page that warns the user of the problem.
6458 =head1 COMPATIBILITY WITH CGI-LIB.PL
6460 To make it easier to port existing programs that use cgi-lib.pl the
6461 compatibility routine "ReadParse" is provided. Porting is simple:
6464 require "cgi-lib.pl";
6466 print "The value of the antique is $in{antique}.\n";
6471 print "The value of the antique is $in{antique}.\n";
6473 CGI.pm's ReadParse() routine creates a tied variable named %in,
6474 which can be accessed to obtain the query variables. Like
6475 ReadParse, you can also provide your own variable. Infrequently
6476 used features of ReadParse, such as the creation of @in and $in
6477 variables, are not supported.
6479 Once you use ReadParse, you can retrieve the query object itself
6483 print $q->textfield(-name=>'wow',
6484 -value=>'does this really work?');
6486 This allows you to start using the more interesting features
6487 of CGI.pm without rewriting your old scripts from scratch.
6489 =head1 AUTHOR INFORMATION
6491 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
6493 This library is free software; you can redistribute it and/or modify
6494 it under the same terms as Perl itself.
6496 Address bug reports and comments to: lstein@cshl.org. When sending
6497 bug reports, please provide the version of CGI.pm, the version of
6498 Perl, the name and version of your Web server, and the name and
6499 version of the operating system you are using. If the problem is even
6500 remotely browser dependent, please provide information about the
6501 affected browers as well.
6505 Thanks very much to:
6509 =item Matt Heffron (heffron@falstaff.css.beckman.com)
6511 =item James Taylor (james.taylor@srs.gov)
6513 =item Scott Anguish <sanguish@digifix.com>
6515 =item Mike Jewell (mlj3u@virginia.edu)
6517 =item Timothy Shimmin (tes@kbs.citri.edu.au)
6519 =item Joergen Haegg (jh@axis.se)
6521 =item Laurent Delfosse (delfosse@delfosse.com)
6523 =item Richard Resnick (applepi1@aol.com)
6525 =item Craig Bishop (csb@barwonwater.vic.gov.au)
6527 =item Tony Curtis (tc@vcpc.univie.ac.at)
6529 =item Tim Bunce (Tim.Bunce@ig.co.uk)
6531 =item Tom Christiansen (tchrist@convex.com)
6533 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
6535 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
6537 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
6539 =item Stephen Dahmen (joyfire@inxpress.net)
6541 =item Ed Jordan (ed@fidalgo.net)
6543 =item David Alan Pisoni (david@cnation.com)
6545 =item Doug MacEachern (dougm@opengroup.org)
6547 =item Robin Houston (robin@oneworld.org)
6549 =item ...and many many more...
6551 for suggestions and bug fixes.
6555 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
6558 #!/usr/local/bin/perl
6564 print $query->header;
6565 print $query->start_html("Example CGI.pm Form");
6566 print "<H1> Example CGI.pm Form</H1>\n";
6567 &print_prompt($query);
6570 print $query->end_html;
6575 print $query->start_form;
6576 print "<EM>What's your name?</EM><BR>";
6577 print $query->textfield('name');
6578 print $query->checkbox('Not my real name');
6580 print "<P><EM>Where can you find English Sparrows?</EM><BR>";
6581 print $query->checkbox_group(
6582 -name=>'Sparrow locations',
6583 -values=>[England,France,Spain,Asia,Hoboken],
6585 -defaults=>[England,Asia]);
6587 print "<P><EM>How far can they fly?</EM><BR>",
6588 $query->radio_group(
6590 -values=>['10 ft','1 mile','10 miles','real far'],
6591 -default=>'1 mile');
6593 print "<P><EM>What's your favorite color?</EM> ";
6594 print $query->popup_menu(-name=>'Color',
6595 -values=>['black','brown','red','yellow'],
6598 print $query->hidden('Reference','Monty Python and the Holy Grail');
6600 print "<P><EM>What have you got there?</EM><BR>";
6601 print $query->scrolling_list(
6602 -name=>'possessions',
6603 -values=>['A Coconut','A Grail','An Icon',
6604 'A Sword','A Ticket'],
6608 print "<P><EM>Any parting comments?</EM><BR>";
6609 print $query->textarea(-name=>'Comments',
6613 print "<P>",$query->reset;
6614 print $query->submit('Action','Shout');
6615 print $query->submit('Action','Scream');
6616 print $query->endform;
6624 print "<H2>Here are the current settings in this form</H2>";
6626 foreach $key ($query->param) {
6627 print "<STRONG>$key</STRONG> -> ";
6628 @values = $query->param($key);
6629 print join(", ",@values),"<BR>\n";
6636 <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
6637 <A HREF="/">Home Page</A>
6643 This module has grown large and monolithic. Furthermore it's doing many
6644 things, such as handling URLs, parsing CGI input, writing HTML, etc., that
6645 are also done in the LWP modules. It should be discarded in favor of
6646 the CGI::* modules, but somehow I continue to work on it.
6648 Note that the code is truly contorted in order to avoid spurious
6649 warnings when programs are run with the B<-w> switch.
6653 L<CGI::Carp>, L<URI::URL>, L<CGI::Request>, L<CGI::MiniSvr>,
6654 L<CGI::Base>, L<CGI::Form>, L<CGI::Push>, L<CGI::Fast>,