4 # See the bottom of this file for the POD documentation. Search for the
7 # You can run this file through either pod2man or pod2html to produce pretty
8 # documentation in manual or html file format (these utilities are part of the
9 # Perl 5 distribution).
11 # Copyright 1995-1998 Lincoln D. Stein. All rights reserved.
12 # It may be used and modified freely, but I do request that this copyright
13 # notice remain attached to the file. You may modify this module as you
14 # wish, but if you redistribute a modified version, please attach a note
15 # listing the modifications you have made.
17 # The most recent version and complete docs are available at:
18 # http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
19 # ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
21 $CGI::revision = '$Id: CGI.pm,v 1.32 1998/05/28 21:55:43 lstein Exp lstein $';
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';
28 # >>>>> Here are some globals that you might want to adjust <<<<<<
29 sub initialize_globals {
30 # Set this to 1 to enable copious autoloader debugging messages
33 # Change this to the preferred DTD to print in start_html()
34 # or use default_dtd('text of DTD to use');
35 $DEFAULT_DTD = '-//IETF//DTD HTML//EN';
37 # Set this to 1 to enable NPH scripts
41 # 3) print header(-nph=>1)
44 # Set this to 1 to disable debugging from the
48 # Set this to 1 to make the temporary files created
49 # during file uploads safe from prying eyes
51 # 1) use CGI qw(:private_tempfiles)
52 # 2) $CGI::private_tempfiles(1);
53 $PRIVATE_TEMPFILES = 0;
55 # Set this to a positive value to limit the size of a POSTing
56 # to a certain number of bytes:
59 # Change this to 1 to disable uploads entirely:
62 # Other globals that you shouldn't worry about.
68 # prevent complaints by mod_perl
72 # ------------------ START OF THE LIBRARY ------------
77 # FIGURE OUT THE OS WE'RE RUNNING UNDER
78 # Some systems support the $^O variable. If not
79 # available then require() the Config library
83 $OS = $Config::Config{'osname'};
88 } elsif ($OS=~/vms/i) {
90 } elsif ($OS=~/^MacOS$/i) {
92 } elsif ($OS=~/os2/i) {
98 # Some OS logic. Binary mode enabled on DOS, NT and VMS
99 $needs_binmode = $OS=~/^(WINDOWS|VMS|OS2)/;
101 # This is the default class for the CGI object to use when all else fails.
102 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
104 # This is where to look for autoloaded routines.
105 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
107 # The path separator is a slash, backslash or semicolon, depending
110 UNIX=>'/', OS2=>'\\', WINDOWS=>'\\', MACINTOSH=>':', VMS=>'/'
113 # This no longer seems to be necessary
114 # Turn on NPH scripts by default when running under IIS server!
115 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
116 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
118 # Turn on special checking for Doug MacEachern's modperl
119 if (defined($ENV{'GATEWAY_INTERFACE'}) &&
120 ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//))
125 # Turn on special checking for ActiveState's PerlEx
126 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
128 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
129 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
130 # and sometimes CR). The most popular VMS web server
131 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
132 # use ASCII, so \015\012 means something different. I find this all
134 $EBCDIC = "\t" ne "\011";
143 if ($needs_binmode) {
144 $CGI::DefaultClass->binmode(main::STDOUT);
145 $CGI::DefaultClass->binmode(main::STDIN);
146 $CGI::DefaultClass->binmode(main::STDERR);
150 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
151 tt u i b blockquote pre img a address cite samp dfn html head
152 base body Link nextid title meta kbd start_html end_html
153 input Select option comment/],
154 ':html3'=>[qw/div table caption th td TR Tr sup sub strike applet Param
155 embed basefont style span layer ilayer font frameset frame script small big/],
156 ':netscape'=>[qw/blink fontsize center/],
157 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
158 submit reset defaults radio_group popup_menu button autoEscape
159 scrolling_list image_button start_form end_form startform endform
160 start_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
161 ':cgi'=>[qw/param path_info path_translated url self_url script_name cookie dump
162 raw_cookie request_method query_string accept user_agent remote_host
163 remote_addr referer server_name server_software server_port server_protocol
164 virtual_host remote_ident auth_type http use_named_parameters
165 save_parameters restore_parameters param_fetch
166 remote_user user_name header redirect import_names put Delete Delete_all url_param/],
167 ':ssl' => [qw/https/],
168 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam/],
169 ':html' => [qw/:html2 :html3 :netscape/],
170 ':standard' => [qw/:html2 :html3 :form :cgi/],
171 ':push' => [qw/multipart_init multipart_start multipart_end/],
172 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal/]
175 # to import symbols into caller
179 # This causes modules to clash.
183 $self->_setup_symbols(@_);
184 my ($callpack, $callfile, $callline) = caller;
186 # To allow overriding, search through the packages
187 # Till we find one in which the correct subroutine is defined.
188 my @packages = ($self,@{"$self\:\:ISA"});
189 foreach $sym (keys %EXPORT) {
191 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
192 foreach $pck (@packages) {
193 if (defined(&{"$pck\:\:$sym"})) {
198 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
204 $pack->_setup_symbols('-compile',@_);
210 return ($tag) unless $EXPORT_TAGS{$tag};
211 foreach (@{$EXPORT_TAGS{$tag}}) {
212 push(@r,&expand_tags($_));
218 # The new routine. This will check the current environment
219 # for an existing query string, and initialize itself, if so.
222 my($class,$initializer) = @_;
224 bless $self,ref $class || $class || $DefaultClass;
226 Apache->request->register_cleanup(\&CGI::_reset_globals);
229 $self->_reset_globals if $PERLEX;
230 $self->init($initializer);
234 # We provide a DESTROY method so that the autoloader
235 # doesn't bother trying to find it.
239 # Returns the value(s)of a named parameter.
240 # If invoked in a list context, returns the
241 # entire list. Otherwise returns the first
242 # member of the list.
243 # If name is not provided, return a list of all
244 # the known parameters names available.
245 # If more than one argument is provided, the
246 # second and subsequent arguments are used to
247 # set the value of the parameter.
250 my($self,@p) = self_or_default(@_);
251 return $self->all_parameters unless @p;
252 my($name,$value,@other);
254 # For compatibility between old calling style and use_named_parameters() style,
255 # we have to special case for a single parameter present.
257 ($name,$value,@other) = $self->rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
260 if (substr($p[0],0,1) eq '-' || $self->use_named_parameters) {
261 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
263 foreach ($value,@other) {
264 push(@values,$_) if defined($_);
267 # If values is provided, then we set it.
269 $self->add_parameter($name);
270 $self->{$name}=[@values];
276 return () unless defined($name) && $self->{$name};
277 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
280 sub self_or_default {
281 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
282 unless (defined($_[0]) &&
283 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
285 $Q = $CGI::DefaultClass->new unless defined($Q);
292 local $^W=0; # prevent a warning
293 if (defined($_[0]) &&
294 (substr(ref($_[0]),0,3) eq 'CGI'
295 || UNIVERSAL::isa($_[0],'CGI'))) {
298 return ($DefaultClass,@_);
302 ########################################
303 # THESE METHODS ARE MORE OR LESS PRIVATE
304 # GO TO THE __DATA__ SECTION TO SEE MORE
306 ########################################
308 # Initialize the query object from the environment.
309 # If a parameter list is found, this object will be set
310 # to an associative array in which parameter names are keys
311 # and the values are stored as lists
312 # If a keyword list is found, this method creates a bogus
313 # parameter list with the single parameter 'keywords'.
316 my($self,$initializer) = @_;
317 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
319 # if we get called more than once, we want to initialize
320 # ourselves from the original query (which may be gone
321 # if it was read from STDIN originally.)
322 if (defined(@QUERY_PARAM) && !defined($initializer)) {
323 foreach (@QUERY_PARAM) {
324 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
329 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
330 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
331 die "Client attempted to POST $content_length bytes, but POSTs are limited to $POST_MAX"
332 if ($POST_MAX > 0) && ($content_length > $POST_MAX);
333 $fh = to_filehandle($initializer) if $initializer;
337 # Process multipart postings, but only if the initializer is
340 && defined($ENV{'CONTENT_TYPE'})
341 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
342 && !defined($initializer)
344 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";]+)\"?/;
345 $self->read_multipart($boundary,$content_length);
349 # If initializer is defined, then read parameters
351 if (defined($initializer)) {
352 if (UNIVERSAL::isa($initializer,'CGI')) {
353 $query_string = $initializer->query_string;
356 if (ref($initializer) && ref($initializer) eq 'HASH') {
357 foreach (keys %$initializer) {
358 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
363 if (defined($fh) && ($fh ne '')) {
369 # massage back into standard format
370 if ("@lines" =~ /=/) {
371 $query_string=join("&",@lines);
373 $query_string=join("+",@lines);
378 # last chance -- treat it as a string
379 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
380 $query_string = $initializer;
385 # If method is GET or HEAD, fetch the query from
387 if ($meth=~/^(GET|HEAD)$/) {
388 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
392 if ($meth eq 'POST') {
393 $self->read_from_client(\*STDIN,\$query_string,$content_length,0)
394 if $content_length > 0;
395 # Some people want to have their cake and eat it too!
396 # Uncomment this line to have the contents of the query string
397 # APPENDED to the POST data.
398 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
402 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
403 # Check the command line and then the standard input for data.
404 # We use the shellwords package in order to behave the way that
405 # UN*X programmers expect.
406 $query_string = read_from_cmdline() unless $NO_DEBUG;
409 # We now have the query string in hand. We do slightly
410 # different things for keyword lists and parameter lists.
411 if ($query_string ne '') {
412 if ($query_string =~ /=/) {
413 $self->parse_params($query_string);
415 $self->add_parameter('keywords');
416 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
420 # Special case. Erase everything if there is a field named
422 if ($self->param('.defaults')) {
426 # Associative array containing our defined fieldnames
427 $self->{'.fieldnames'} = {};
428 foreach ($self->param('.cgifields')) {
429 $self->{'.fieldnames'}->{$_}++;
432 # Clear out our default submission button flag if present
433 $self->delete('.submit');
434 $self->delete('.cgifields');
435 $self->save_request unless $initializer;
438 # FUNCTIONS TO OVERRIDE:
439 # Turn a string into a filehandle
442 return undef unless $thingy;
443 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
444 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
447 while (my $package = caller($caller++)) {
448 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
449 return $tmp if defined(fileno($tmp));
455 # send output to the browser
457 my($self,@p) = self_or_default(@_);
461 # print to standard output (for overriding in mod_perl)
467 # unescape URL-encoded data
469 shift() if ref($_[0]);
470 my $todecode = shift;
471 return undef unless defined($todecode);
472 $todecode =~ tr/+/ /; # pluses become spaces
473 $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
479 shift() if ref($_[0]) || $_[0] eq $DefaultClass;
480 my $toencode = shift;
481 return undef unless defined($toencode);
482 $toencode=~s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
488 # We're going to play with the package globals now so that if we get called
489 # again, we initialize ourselves in exactly the same way. This allows
490 # us to have several of these objects.
491 @QUERY_PARAM = $self->param; # save list of parameters
492 foreach (@QUERY_PARAM) {
493 $QUERY_PARAM{$_}=$self->{$_};
498 my($self,$tosplit) = @_;
499 my(@pairs) = split('&',$tosplit);
502 ($param,$value) = split('=',$_,2);
503 $param = unescape($param);
504 $value = unescape($value);
505 $self->add_parameter($param);
506 push (@{$self->{$param}},$value);
512 push (@{$self->{'.parameters'}},$param)
513 unless defined($self->{$param});
518 return () unless defined($self) && $self->{'.parameters'};
519 return () unless @{$self->{'.parameters'}};
520 return @{$self->{'.parameters'}};
523 # put a filehandle into binary mode (DOS)
525 CORE::binmode($_[1]);
532 # handle various cases in which we're called
533 # most of this bizarre stuff is to avoid -w errors
535 (!ref(\$_[0]) && \$_[0] eq \$CGI::DefaultClass) ||
537 (substr(ref(\$_[0]),0,3) eq 'CGI' ||
538 UNIVERSAL::isa(\$_[0],'CGI')));
541 if (ref(\$_[0]) && ref(\$_[0]) eq 'HASH') {
542 my(\@attr) = make_attributes( '',shift() );
543 \$attr = " \@attr" if \@attr;
545 my(\$tag,\$untag) = ("\U<$tagname\E\$attr>","\U</$tagname>\E");
546 return \$tag unless \@_;
547 my \@result = map { "\$tag\$_\$untag" } (ref(\$_[0]) eq 'ARRAY') ? \@{\$_[0]} : "\@_";
554 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
555 my $func = &_compile;
560 # Smart rearrangement of parameters to allow named parameter
561 # calling. We do the rearangement if:
562 # 1. The first parameter begins with a -
563 # 2. The use_named_parameters() method returns true
565 my($self,$order,@param) = @_;
566 return () unless @param;
568 if (ref($param[0]) eq 'HASH') {
569 @param = %{$param[0]};
572 unless (defined($param[0]) && substr($param[0],0,1) eq '-')
573 || $self->use_named_parameters;
576 # map parameters into positional indices
580 foreach (ref($_) eq 'ARRAY' ? @$_ : $_) { $pos{$_} = $i; }
584 my (@result,%leftover);
585 $#result = $#$order; # preextend
587 my $key = uc(shift(@param));
589 if (exists $pos{$key}) {
590 $result[$pos{$key}] = shift(@param);
592 $leftover{$key} = shift(@param);
596 push (@result,$self->make_attributes(\%leftover)) if %leftover;
601 my($func) = $AUTOLOAD;
602 my($pack,$func_name);
604 local($1,$2); # this fixes an obscure variable suicide problem.
605 $func=~/(.+)::([^:]+)$/;
606 ($pack,$func_name) = ($1,$2);
607 $pack=~s/::SUPER$//; # fix another obscure problem
608 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
609 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
611 my($sub) = \%{"$pack\:\:SUBS"};
613 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
614 eval "package $pack; $$auto";
616 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
618 my($code) = $sub->{$func_name};
620 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
622 if ($EXPORT{':any'} ||
624 $EXPORT{$func_name} ||
625 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
626 && $EXPORT_OK{$func_name}) {
627 $code = _make_tag_func($func_name);
630 die "Undefined subroutine $AUTOLOAD\n" unless $code;
631 eval "package $pack; $code";
637 delete($sub->{$func_name}); #free storage
638 return "$pack\:\:$func_name";
641 sub _reset_globals { initialize_globals(); }
647 $NPH++, next if /^[:-]nph$/;
648 $NO_DEBUG++, next if /^[:-]no_?[Dd]ebug$/;
649 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
650 $EXPORT{$_}++, next if /^[:-]any$/;
651 $compile++, next if /^[:-]compile$/;
653 # This is probably extremely evil code -- to be deleted
655 if (/^[-]autoload$/) {
656 my($pkg) = caller(1);
657 *{"${pkg}::AUTOLOAD"} = sub {
658 my($routine) = $AUTOLOAD;
659 $routine =~ s/^.*::/CGI::/;
665 foreach (&expand_tags($_)) {
666 tr/a-zA-Z0-9_//cd; # don't allow weird function names
670 _compile_all(keys %EXPORT) if $compile;
673 ###############################################################################
674 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
675 ###############################################################################
676 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
677 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
681 'URL_ENCODED'=> <<'END_OF_FUNC',
682 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
685 'MULTIPART' => <<'END_OF_FUNC',
686 sub MULTIPART { 'multipart/form-data'; }
689 'SERVER_PUSH' => <<'END_OF_FUNC',
690 sub SERVER_PUSH { 'multipart/x-mixed-replace; boundary="' . shift() . '"'; }
693 'use_named_parameters' => <<'END_OF_FUNC',
694 #### Method: use_named_parameters
695 # Force CGI.pm to use named parameter-style method calls
696 # rather than positional parameters. The same effect
697 # will happen automatically if the first parameter
699 sub use_named_parameters {
700 my($self,$use_named) = self_or_default(@_);
701 return $self->{'.named'} unless defined ($use_named);
703 # stupidity to avoid annoying warnings
704 return $self->{'.named'}=$use_named;
708 'new_MultipartBuffer' => <<'END_OF_FUNC',
709 # Create a new multipart buffer
710 sub new_MultipartBuffer {
711 my($self,$boundary,$length,$filehandle) = @_;
712 return MultipartBuffer->new($self,$boundary,$length,$filehandle);
716 'read_from_client' => <<'END_OF_FUNC',
717 # Read data from a file handle
718 sub read_from_client {
719 my($self, $fh, $buff, $len, $offset) = @_;
720 local $^W=0; # prevent a warning
721 return undef unless defined($fh);
722 return read($fh, $$buff, $len, $offset);
726 'delete' => <<'END_OF_FUNC',
728 # Deletes the named parameter entirely.
731 my($self,$name) = self_or_default(@_);
732 delete $self->{$name};
733 delete $self->{'.fieldnames'}->{$name};
734 @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
735 return wantarray ? () : undef;
739 #### Method: import_names
740 # Import all parameters into the given namespace.
741 # Assumes namespace 'Q' if not specified
743 'import_names' => <<'END_OF_FUNC',
745 my($self,$namespace,$delete) = self_or_default(@_);
746 $namespace = 'Q' unless defined($namespace);
747 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
748 if ($delete || $MOD_PERL) {
749 # can anyone find an easier way to do this?
750 foreach (keys %{"${namespace}::"}) {
751 local *symbol = "${namespace}::${_}";
757 my($param,@value,$var);
758 foreach $param ($self->param) {
759 # protect against silly names
760 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
761 $var =~ s/^(?=\d)/_/;
762 local *symbol = "${namespace}::$var";
763 @value = $self->param($param);
770 #### Method: keywords
771 # Keywords acts a bit differently. Calling it in a list context
772 # returns the list of keywords.
773 # Calling it in a scalar context gives you the size of the list.
775 'keywords' => <<'END_OF_FUNC',
777 my($self,@values) = self_or_default(@_);
778 # If values is provided, then we set it.
779 $self->{'keywords'}=[@values] if defined(@values);
780 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
785 # These are some tie() interfaces for compatibility
786 # with Steve Brenner's cgi-lib.pl routines
787 'ReadParse' => <<'END_OF_FUNC',
797 return scalar(keys %in);
801 'PrintHeader' => <<'END_OF_FUNC',
803 my($self) = self_or_default(@_);
804 return $self->header();
808 'HtmlTop' => <<'END_OF_FUNC',
810 my($self,@p) = self_or_default(@_);
811 return $self->start_html(@p);
815 'HtmlBot' => <<'END_OF_FUNC',
817 my($self,@p) = self_or_default(@_);
818 return $self->end_html(@p);
822 'SplitParam' => <<'END_OF_FUNC',
825 my (@params) = split ("\0", $param);
826 return (wantarray ? @params : $params[0]);
830 'MethGet' => <<'END_OF_FUNC',
832 return request_method() eq 'GET';
836 'MethPost' => <<'END_OF_FUNC',
838 return request_method() eq 'POST';
842 'TIEHASH' => <<'END_OF_FUNC',
844 return $Q || new CGI;
848 'STORE' => <<'END_OF_FUNC',
850 $_[0]->param($_[1],split("\0",$_[2]));
854 'FETCH' => <<'END_OF_FUNC',
856 return $_[0] if $_[1] eq 'CGI';
857 return undef unless defined $_[0]->param($_[1]);
858 return join("\0",$_[0]->param($_[1]));
862 'FIRSTKEY' => <<'END_OF_FUNC',
864 $_[0]->{'.iterator'}=0;
865 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
869 'NEXTKEY' => <<'END_OF_FUNC',
871 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
875 'EXISTS' => <<'END_OF_FUNC',
877 exists $_[0]->{$_[1]};
881 'DELETE' => <<'END_OF_FUNC',
883 $_[0]->delete($_[1]);
887 'CLEAR' => <<'END_OF_FUNC',
895 # Append a new value to an existing query
900 my($name,$value) = $self->rearrange([NAME,[VALUE,VALUES]],@p);
901 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
903 $self->add_parameter($name);
904 push(@{$self->{$name}},@values);
906 return $self->param($name);
910 #### Method: delete_all
911 # Delete all parameters
913 'delete_all' => <<'EOF',
915 my($self) = self_or_default(@_);
922 my($self,@p) = self_or_default(@_);
927 'Delete_all' => <<'EOF',
929 my($self,@p) = self_or_default(@_);
930 $self->delete_all(@p);
934 #### Method: autoescape
935 # If you want to turn off the autoescaping features,
936 # call this method with undef as the argument
937 'autoEscape' => <<'END_OF_FUNC',
939 my($self,$escape) = self_or_default(@_);
940 $self->{'dontescape'}=!$escape;
946 # Return the current version
948 'version' => <<'END_OF_FUNC',
954 'make_attributes' => <<'END_OF_FUNC',
955 sub make_attributes {
956 my($self,$attr) = @_;
957 return () unless $attr && ref($attr) && ref($attr) eq 'HASH';
959 foreach (keys %{$attr}) {
961 $key=~s/^\-//; # get rid of initial - if present
962 $key=~tr/a-z_/A-Z-/; # parameters are upper case, use dashes
963 push(@att,defined($attr->{$_}) ? qq/$key="$attr->{$_}"/ : qq/$key/);
969 #### Method: url_param
970 # Return a parameter in the QUERY_STRING, regardless of
971 # whether this was a POST or a GET
973 'url_param' => <<'END_OF_FUNC',
975 my ($self,@p) = self_or_default(@_);
976 my $name = shift(@p);
977 return undef unless exists($ENV{QUERY_STRING});
978 unless (exists($self->{'.url_param'})) {
979 $self->{'.url_param'}={}; # empty hash
980 if ($ENV{QUERY_STRING} =~ /=/) {
981 my(@pairs) = split('&',$ENV{QUERY_STRING});
984 ($param,$value) = split('=',$_,2);
985 $param = unescape($param);
986 $value = unescape($value);
987 push(@{$self->{'.url_param'}->{$param}},$value);
990 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
993 return keys %{$self->{'.url_param'}} unless defined($name);
994 return () unless $self->{'.url_param'}->{$name};
995 return wantarray ? @{$self->{'.url_param'}->{$name}}
996 : $self->{'.url_param'}->{$name}->[0];
1001 # Returns a string in which all the known parameter/value
1002 # pairs are represented as nested lists, mainly for the purposes
1005 'dump' => <<'END_OF_FUNC',
1007 my($self) = self_or_default(@_);
1008 my($param,$value,@result);
1009 return '<UL></UL>' unless $self->param;
1010 push(@result,"<UL>");
1011 foreach $param ($self->param) {
1012 my($name)=$self->escapeHTML($param);
1013 push(@result,"<LI><STRONG>$param</STRONG>");
1014 push(@result,"<UL>");
1015 foreach $value ($self->param($param)) {
1016 $value = $self->escapeHTML($value);
1017 push(@result,"<LI>$value");
1019 push(@result,"</UL>");
1021 push(@result,"</UL>\n");
1022 return join("\n",@result);
1026 #### Method as_string
1028 # synonym for "dump"
1030 'as_string' => <<'END_OF_FUNC',
1037 # Write values out to a filehandle in such a way that they can
1038 # be reinitialized by the filehandle form of the new() method
1040 'save' => <<'END_OF_FUNC',
1042 my($self,$filehandle) = self_or_default(@_);
1043 $filehandle = to_filehandle($filehandle);
1045 local($,) = ''; # set print field separator back to a sane value
1046 foreach $param ($self->param) {
1047 my($escaped_param) = escape($param);
1049 foreach $value ($self->param($param)) {
1050 print $filehandle "$escaped_param=",escape($value),"\n";
1053 print $filehandle "=\n"; # end of record
1058 #### Method: save_parameters
1059 # An alias for save() that is a better name for exportation.
1060 # Only intended to be used with the function (non-OO) interface.
1062 'save_parameters' => <<'END_OF_FUNC',
1063 sub save_parameters {
1065 return save(to_filehandle($fh));
1069 #### Method: restore_parameters
1070 # A way to restore CGI parameters from an initializer.
1071 # Only intended to be used with the function (non-OO) interface.
1073 'restore_parameters' => <<'END_OF_FUNC',
1074 sub restore_parameters {
1075 $Q = $CGI::DefaultClass->new(@_);
1079 #### Method: multipart_init
1080 # Return a Content-Type: style header for server-push
1081 # This has to be NPH, and it is advisable to set $| = 1
1083 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1086 'multipart_init' => <<'END_OF_FUNC',
1087 sub multipart_init {
1088 my($self,@p) = self_or_default(@_);
1089 my($boundary,@other) = $self->rearrange([BOUNDARY],@p);
1090 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1091 $self->{'separator'} = "\n--$boundary\n";
1092 $type = SERVER_PUSH($boundary);
1093 return $self->header(
1096 (map { split "=", $_, 2 } @other),
1097 ) . $self->multipart_end;
1102 #### Method: multipart_start
1103 # Return a Content-Type: style header for server-push, start of section
1105 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1108 'multipart_start' => <<'END_OF_FUNC',
1109 sub multipart_start {
1110 my($self,@p) = self_or_default(@_);
1111 my($type,@other) = $self->rearrange([TYPE],@p);
1112 $type = $type || 'text/html';
1113 return $self->header(
1115 (map { split "=", $_, 2 } @other),
1121 #### Method: multipart_end
1122 # Return a Content-Type: style header for server-push, end of section
1124 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1127 'multipart_end' => <<'END_OF_FUNC',
1129 my($self,@p) = self_or_default(@_);
1130 return $self->{'separator'};
1136 # Return a Content-Type: style header
1139 'header' => <<'END_OF_FUNC',
1141 my($self,@p) = self_or_default(@_);
1144 my($type,$status,$cookie,$target,$expires,$nph,@other) =
1145 $self->rearrange([TYPE,STATUS,[COOKIE,COOKIES],TARGET,EXPIRES,NPH],@p);
1148 # rearrange() was designed for the HTML portion, so we
1149 # need to fix it up a little.
1151 next unless my($header,$value) = /([^\s=]+)=\"?([^\"]+)\"?/;
1152 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ": $value"/e;
1155 $type = $type || 'text/html';
1157 # Maybe future compatibility. Maybe not.
1158 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1159 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1161 push(@header,"Status: $status") if $status;
1162 push(@header,"Window-Target: $target") if $target;
1163 # push all the cookies -- there may be several
1165 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1167 push(@header,"Set-Cookie: " . (UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_));
1170 # if the user indicates an expiration time, then we need
1171 # both an Expires and a Date header (so that the browser is
1173 push(@header,"Expires: " . expires($expires,'http'))
1175 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie;
1176 push(@header,"Pragma: no-cache") if $self->cache();
1177 push(@header,@other);
1178 push(@header,"Content-Type: $type");
1180 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1181 if ($MOD_PERL and not $nph) {
1182 my $r = Apache->request;
1183 $r->send_cgi_header($header);
1192 # Control whether header() will produce the no-cache
1195 'cache' => <<'END_OF_FUNC',
1197 my($self,$new_value) = self_or_default(@_);
1198 $new_value = '' unless $new_value;
1199 if ($new_value ne '') {
1200 $self->{'cache'} = $new_value;
1202 return $self->{'cache'};
1207 #### Method: redirect
1208 # Return a Location: style header
1211 'redirect' => <<'END_OF_FUNC',
1213 my($self,@p) = self_or_default(@_);
1214 my($url,$target,$cookie,$nph,@other) = $self->rearrange([[LOCATION,URI,URL],TARGET,COOKIE,NPH],@p);
1215 $url = $url || $self->self_url;
1217 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1219 '-Status'=>'302 Moved',
1222 unshift(@o,'-Target'=>$target) if $target;
1223 unshift(@o,'-Cookie'=>$cookie) if $cookie;
1224 return $self->header(@o);
1229 #### Method: start_html
1230 # Canned HTML header
1233 # $title -> (optional) The title for this HTML document (-title)
1234 # $author -> (optional) e-mail address of the author (-author)
1235 # $base -> (optional) if set to true, will enter the BASE address of this document
1236 # for resolving relative references (-base)
1237 # $xbase -> (optional) alternative base at some remote location (-xbase)
1238 # $target -> (optional) target window to load all links into (-target)
1239 # $script -> (option) Javascript code (-script)
1240 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1241 # $meta -> (optional) Meta information tags
1242 # $head -> (optional) any other elements you'd like to incorporate into the <HEAD> tag
1243 # (a scalar or array ref)
1244 # $style -> (optional) reference to an external style sheet
1245 # @other -> (optional) any other named parameters you'd like to incorporate into
1248 'start_html' => <<'END_OF_FUNC',
1250 my($self,@p) = &self_or_default(@_);
1251 my($title,$author,$base,$xbase,$script,$noscript,$target,$meta,$head,$style,$dtd,@other) =
1252 $self->rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD],@p);
1254 # strangely enough, the title needs to be escaped as HTML
1255 # while the author needs to be escaped as a URL
1256 $title = $self->escapeHTML($title || 'Untitled Document');
1257 $author = $self->escape($author);
1259 $dtd = $DEFAULT_DTD unless $dtd && $dtd =~ m|^-//|;
1260 push(@result,qq(<!DOCTYPE HTML PUBLIC "$dtd">)) if $dtd;
1261 push(@result,"<HTML><HEAD><TITLE>$title</TITLE>");
1262 push(@result,"<LINK REV=MADE HREF=\"mailto:$author\">") if defined $author;
1264 if ($base || $xbase || $target) {
1265 my $href = $xbase || $self->url('-path'=>1);
1266 my $t = $target ? qq/ TARGET="$target"/ : '';
1267 push(@result,qq/<BASE HREF="$href"$t>/);
1270 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1271 foreach (keys %$meta) { push(@result,qq(<META NAME="$_" CONTENT="$meta->{$_}">)); }
1274 push(@result,ref($head) ? @$head : $head) if $head;
1276 # handle the infrequently-used -style and -script parameters
1277 push(@result,$self->_style($style)) if defined $style;
1278 push(@result,$self->_script($script)) if defined $script;
1280 # handle -noscript parameter
1281 push(@result,<<END) if $noscript;
1287 my($other) = @other ? " @other" : '';
1288 push(@result,"</HEAD><BODY$other>");
1289 return join("\n",@result);
1294 # internal method for generating a CSS style section
1296 '_style' => <<'END_OF_FUNC',
1298 my ($self,$style) = @_;
1300 my $type = 'text/css';
1302 my($src,$code,$stype,@other) =
1303 $self->rearrange([SRC,CODE,TYPE],
1304 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1305 ref($style) eq 'ARRAY' ? @$style : %$style);
1306 $type = $stype if $stype;
1307 push(@result,qq/<LINK REL="stylesheet" HREF="$src">/) if $src;
1308 push(@result,style({'type'=>$type},"<!--\n$code\n-->")) if $code;
1310 push(@result,style({'type'=>$type},"<!--\n$style\n-->"));
1317 '_script' => <<'END_OF_FUNC',
1319 my ($self,$script) = @_;
1321 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1322 foreach $script (@scripts) {
1323 my($src,$code,$language);
1324 if (ref($script)) { # script is a hash
1325 ($src,$code,$language) =
1326 $self->rearrange([SRC,CODE,LANGUAGE],
1327 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1328 ref($style) eq 'ARRAY' ? @$script : %$script);
1331 ($src,$code,$language) = ('',$script,'JavaScript');
1334 push(@satts,'src'=>$src) if $src;
1335 push(@satts,'language'=>$language || 'JavaScript');
1336 $code = "<!-- Hide script\n$code\n// End script hiding -->"
1337 if $code && $language=~/javascript/i;
1338 $code = "<!-- Hide script\n$code\n\# End script hiding -->"
1339 if $code && $language=~/perl/i;
1340 push(@result,script({@satts},$code));
1346 #### Method: end_html
1347 # End an HTML document.
1348 # Trivial method for completeness. Just returns "</BODY>"
1350 'end_html' => <<'END_OF_FUNC',
1352 return "</BODY></HTML>";
1357 ################################
1358 # METHODS USED IN BUILDING FORMS
1359 ################################
1361 #### Method: isindex
1362 # Just prints out the isindex tag.
1364 # $action -> optional URL of script to run
1366 # A string containing a <ISINDEX> tag
1367 'isindex' => <<'END_OF_FUNC',
1369 my($self,@p) = self_or_default(@_);
1370 my($action,@other) = $self->rearrange([ACTION],@p);
1371 $action = qq/ACTION="$action"/ if $action;
1372 my($other) = @other ? " @other" : '';
1373 return "<ISINDEX $action$other>";
1378 #### Method: startform
1381 # $method -> optional submission method to use (GET or POST)
1382 # $action -> optional URL of script to run
1383 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1384 'startform' => <<'END_OF_FUNC',
1386 my($self,@p) = self_or_default(@_);
1388 my($method,$action,$enctype,@other) =
1389 $self->rearrange([METHOD,ACTION,ENCTYPE],@p);
1391 $method = $method || 'POST';
1392 $enctype = $enctype || &URL_ENCODED;
1393 $action = $action ? qq/ACTION="$action"/ : $method eq 'GET' ?
1394 'ACTION="'.$self->script_name.'"' : '';
1395 my($other) = @other ? " @other" : '';
1396 $self->{'.parametersToAdd'}={};
1397 return qq/<FORM METHOD="$method" $action ENCTYPE="$enctype"$other>\n/;
1402 #### Method: start_form
1403 # synonym for startform
1404 'start_form' => <<'END_OF_FUNC',
1411 #### Method: start_multipart_form
1412 # synonym for startform
1413 'start_multipart_form' => <<'END_OF_FUNC',
1414 sub start_multipart_form {
1415 my($self,@p) = self_or_default(@_);
1416 if ($self->use_named_parameters ||
1417 (defined($param[0]) && substr($param[0],0,1) eq '-')) {
1419 $p{'-enctype'}=&MULTIPART;
1420 return $self->startform(%p);
1422 my($method,$action,@other) =
1423 $self->rearrange([METHOD,ACTION],@p);
1424 return $self->startform($method,$action,&MULTIPART,@other);
1430 #### Method: endform
1432 'endform' => <<'END_OF_FUNC',
1434 my($self,@p) = self_or_default(@_);
1435 return ($self->get_fields,"</FORM>");
1440 #### Method: end_form
1441 # synonym for endform
1442 'end_form' => <<'END_OF_FUNC',
1449 '_textfield' => <<'END_OF_FUNC',
1451 my($self,$tag,@p) = self_or_default(@_);
1452 my($name,$default,$size,$maxlength,$override,@other) =
1453 $self->rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1455 my $current = $override ? $default :
1456 (defined($self->param($name)) ? $self->param($name) : $default);
1458 $current = defined($current) ? $self->escapeHTML($current) : '';
1459 $name = defined($name) ? $self->escapeHTML($name) : '';
1460 my($s) = defined($size) ? qq/ SIZE=$size/ : '';
1461 my($m) = defined($maxlength) ? qq/ MAXLENGTH=$maxlength/ : '';
1462 my($other) = @other ? " @other" : '';
1463 return qq/<INPUT TYPE="$tag" NAME="$name" VALUE="$current"$s$m$other>/;
1467 #### Method: textfield
1469 # $name -> Name of the text field
1470 # $default -> Optional default value of the field if not
1472 # $size -> Optional width of field in characaters.
1473 # $maxlength -> Optional maximum number of characters.
1475 # A string containing a <INPUT TYPE="text"> field
1477 'textfield' => <<'END_OF_FUNC',
1479 my($self,@p) = self_or_default(@_);
1480 $self->_textfield('text',@p);
1485 #### Method: filefield
1487 # $name -> Name of the file upload field
1488 # $size -> Optional width of field in characaters.
1489 # $maxlength -> Optional maximum number of characters.
1491 # A string containing a <INPUT TYPE="text"> field
1493 'filefield' => <<'END_OF_FUNC',
1495 my($self,@p) = self_or_default(@_);
1496 $self->_textfield('file',@p);
1501 #### Method: password
1502 # Create a "secret password" entry field
1504 # $name -> Name of the field
1505 # $default -> Optional default value of the field if not
1507 # $size -> Optional width of field in characters.
1508 # $maxlength -> Optional maximum characters that can be entered.
1510 # A string containing a <INPUT TYPE="password"> field
1512 'password_field' => <<'END_OF_FUNC',
1513 sub password_field {
1514 my ($self,@p) = self_or_default(@_);
1515 $self->_textfield('password',@p);
1519 #### Method: textarea
1521 # $name -> Name of the text field
1522 # $default -> Optional default value of the field if not
1524 # $rows -> Optional number of rows in text area
1525 # $columns -> Optional number of columns in text area
1527 # A string containing a <TEXTAREA></TEXTAREA> tag
1529 'textarea' => <<'END_OF_FUNC',
1531 my($self,@p) = self_or_default(@_);
1533 my($name,$default,$rows,$cols,$override,@other) =
1534 $self->rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1536 my($current)= $override ? $default :
1537 (defined($self->param($name)) ? $self->param($name) : $default);
1539 $name = defined($name) ? $self->escapeHTML($name) : '';
1540 $current = defined($current) ? $self->escapeHTML($current) : '';
1541 my($r) = $rows ? " ROWS=$rows" : '';
1542 my($c) = $cols ? " COLS=$cols" : '';
1543 my($other) = @other ? " @other" : '';
1544 return qq{<TEXTAREA NAME="$name"$r$c$other>$current</TEXTAREA>};
1550 # Create a javascript button.
1552 # $name -> (optional) Name for the button. (-name)
1553 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1554 # $onclick -> (optional) Text of the JavaScript to run when the button is
1557 # A string containing a <INPUT TYPE="button"> tag
1559 'button' => <<'END_OF_FUNC',
1561 my($self,@p) = self_or_default(@_);
1563 my($label,$value,$script,@other) = $self->rearrange([NAME,[VALUE,LABEL],
1564 [ONCLICK,SCRIPT]],@p);
1566 $label=$self->escapeHTML($label);
1567 $value=$self->escapeHTML($value);
1568 $script=$self->escapeHTML($script);
1571 $name = qq/ NAME="$label"/ if $label;
1572 $value = $value || $label;
1574 $val = qq/ VALUE="$value"/ if $value;
1575 $script = qq/ ONCLICK="$script"/ if $script;
1576 my($other) = @other ? " @other" : '';
1577 return qq/<INPUT TYPE="button"$name$val$script$other>/;
1583 # Create a "submit query" button.
1585 # $name -> (optional) Name for the button.
1586 # $value -> (optional) Value of the button when selected (also doubles as label).
1587 # $label -> (optional) Label printed on the button(also doubles as the value).
1589 # A string containing a <INPUT TYPE="submit"> tag
1591 'submit' => <<'END_OF_FUNC',
1593 my($self,@p) = self_or_default(@_);
1595 my($label,$value,@other) = $self->rearrange([NAME,[VALUE,LABEL]],@p);
1597 $label=$self->escapeHTML($label);
1598 $value=$self->escapeHTML($value);
1600 my($name) = ' NAME=".submit"';
1601 $name = qq/ NAME="$label"/ if defined($label);
1602 $value = defined($value) ? $value : $label;
1604 $val = qq/ VALUE="$value"/ if defined($value);
1605 my($other) = @other ? " @other" : '';
1606 return qq/<INPUT TYPE="submit"$name$val$other>/;
1612 # Create a "reset" button.
1614 # $name -> (optional) Name for the button.
1616 # A string containing a <INPUT TYPE="reset"> tag
1618 'reset' => <<'END_OF_FUNC',
1620 my($self,@p) = self_or_default(@_);
1621 my($label,@other) = $self->rearrange([NAME],@p);
1622 $label=$self->escapeHTML($label);
1623 my($value) = defined($label) ? qq/ VALUE="$label"/ : '';
1624 my($other) = @other ? " @other" : '';
1625 return qq/<INPUT TYPE="reset"$value$other>/;
1630 #### Method: defaults
1631 # Create a "defaults" button.
1633 # $name -> (optional) Name for the button.
1635 # A string containing a <INPUT TYPE="submit" NAME=".defaults"> tag
1637 # Note: this button has a special meaning to the initialization script,
1638 # and tells it to ERASE the current query string so that your defaults
1641 'defaults' => <<'END_OF_FUNC',
1643 my($self,@p) = self_or_default(@_);
1645 my($label,@other) = $self->rearrange([[NAME,VALUE]],@p);
1647 $label=$self->escapeHTML($label);
1648 $label = $label || "Defaults";
1649 my($value) = qq/ VALUE="$label"/;
1650 my($other) = @other ? " @other" : '';
1651 return qq/<INPUT TYPE="submit" NAME=".defaults"$value$other>/;
1656 #### Method: comment
1657 # Create an HTML <!-- comment -->
1658 # Parameters: a string
1659 'comment' => <<'END_OF_FUNC',
1661 my($self,@p) = self_or_CGI(@_);
1662 return "<!-- @p -->";
1666 #### Method: checkbox
1667 # Create a checkbox that is not logically linked to any others.
1668 # The field value is "on" when the button is checked.
1670 # $name -> Name of the checkbox
1671 # $checked -> (optional) turned on by default if true
1672 # $value -> (optional) value of the checkbox, 'on' by default
1673 # $label -> (optional) a user-readable label printed next to the box.
1674 # Otherwise the checkbox name is used.
1676 # A string containing a <INPUT TYPE="checkbox"> field
1678 'checkbox' => <<'END_OF_FUNC',
1680 my($self,@p) = self_or_default(@_);
1682 my($name,$checked,$value,$label,$override,@other) =
1683 $self->rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1685 $value = defined $value ? $value : 'on';
1687 if (!$override && ($self->{'.fieldnames'}->{$name} ||
1688 defined $self->param($name))) {
1689 $checked = grep($_ eq $value,$self->param($name)) ? ' CHECKED' : '';
1691 $checked = $checked ? ' CHECKED' : '';
1693 my($the_label) = defined $label ? $label : $name;
1694 $name = $self->escapeHTML($name);
1695 $value = $self->escapeHTML($value);
1696 $the_label = $self->escapeHTML($the_label);
1697 my($other) = @other ? " @other" : '';
1698 $self->register_parameter($name);
1700 <INPUT TYPE="checkbox" NAME="$name" VALUE="$value"$checked$other>$the_label
1706 #### Method: checkbox_group
1707 # Create a list of logically-linked checkboxes.
1709 # $name -> Common name for all the check boxes
1710 # $values -> A pointer to a regular array containing the
1711 # values for each checkbox in the group.
1712 # $defaults -> (optional)
1713 # 1. If a pointer to a regular array of checkbox values,
1714 # then this will be used to decide which
1715 # checkboxes to turn on by default.
1716 # 2. If a scalar, will be assumed to hold the
1717 # value of a single checkbox in the group to turn on.
1718 # $linebreak -> (optional) Set to true to place linebreaks
1719 # between the buttons.
1720 # $labels -> (optional)
1721 # A pointer to an associative array of labels to print next to each checkbox
1722 # in the form $label{'value'}="Long explanatory label".
1723 # Otherwise the provided values are used as the labels.
1725 # An ARRAY containing a series of <INPUT TYPE="checkbox"> fields
1727 'checkbox_group' => <<'END_OF_FUNC',
1728 sub checkbox_group {
1729 my($self,@p) = self_or_default(@_);
1731 my($name,$values,$defaults,$linebreak,$labels,$rows,$columns,
1732 $rowheaders,$colheaders,$override,$nolabels,@other) =
1733 $self->rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1734 LINEBREAK,LABELS,ROWS,[COLUMNS,COLS],
1735 ROWHEADERS,COLHEADERS,
1736 [OVERRIDE,FORCE],NOLABELS],@p);
1738 my($checked,$break,$result,$label);
1740 my(%checked) = $self->previous_or_default($name,$defaults,$override);
1742 $break = $linebreak ? "<BR>" : '';
1743 $name=$self->escapeHTML($name);
1745 # Create the elements
1746 my(@elements,@values);
1748 @values = $self->_set_values_and_labels($values,\$labels,$name);
1750 my($other) = @other ? " @other" : '';
1752 $checked = $checked{$_} ? ' CHECKED' : '';
1754 unless (defined($nolabels) && $nolabels) {
1756 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1757 $label = $self->escapeHTML($label);
1759 $_ = $self->escapeHTML($_);
1760 push(@elements,qq/<INPUT TYPE="checkbox" NAME="$name" VALUE="$_"$checked$other>${label}${break}/);
1762 $self->register_parameter($name);
1763 return wantarray ? @elements : join(' ',@elements)
1764 unless defined($columns) || defined($rows);
1765 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1769 # Escape HTML -- used internally
1770 'escapeHTML' => <<'END_OF_FUNC',
1772 my($self,$toencode) = @_;
1773 $toencode = $self unless ref($self);
1774 return undef unless defined($toencode);
1775 return $toencode if ref($self) && $self->{'dontescape'};
1777 $toencode=~s/&/&/g;
1778 $toencode=~s/\"/"/g;
1779 $toencode=~s/>/>/g;
1780 $toencode=~s/</</g;
1785 # unescape HTML -- used internally
1786 'unescapeHTML' => <<'END_OF_FUNC',
1788 my $string = ref($_[0]) ? $_[1] : $_[0];
1789 return undef unless defined($string);
1790 $string=~s/&/&/ig;
1791 $string=~s/"/\"/ig;
1792 $string=~s/>/>/ig;
1793 $string=~s/</</ig;
1794 $string=~s/&#(\d+);/chr($1)/eg;
1795 $string=~s/&#[xX]([0-9a-fA-F]);/chr(hex($1))/eg;
1800 # Internal procedure - don't use
1801 '_tableize' => <<'END_OF_FUNC',
1803 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
1806 if (defined($columns)) {
1807 $rows = int(0.99 + @elements/$columns) unless defined($rows);
1809 if (defined($rows)) {
1810 $columns = int(0.99 + @elements/$rows) unless defined($columns);
1813 # rearrange into a pretty table
1814 $result = "<TABLE>";
1816 unshift(@$colheaders,'') if defined(@$colheaders) && defined(@$rowheaders);
1817 $result .= "<TR>" if defined(@{$colheaders});
1818 foreach (@{$colheaders}) {
1819 $result .= "<TH>$_</TH>";
1821 for ($row=0;$row<$rows;$row++) {
1823 $result .= "<TH>$rowheaders->[$row]</TH>" if defined(@$rowheaders);
1824 for ($column=0;$column<$columns;$column++) {
1825 $result .= "<TD>" . $elements[$column*$rows + $row] . "</TD>"
1826 if defined($elements[$column*$rows + $row]);
1830 $result .= "</TABLE>";
1836 #### Method: radio_group
1837 # Create a list of logically-linked radio buttons.
1839 # $name -> Common name for all the buttons.
1840 # $values -> A pointer to a regular array containing the
1841 # values for each button in the group.
1842 # $default -> (optional) Value of the button to turn on by default. Pass '-'
1843 # to turn _nothing_ on.
1844 # $linebreak -> (optional) Set to true to place linebreaks
1845 # between the buttons.
1846 # $labels -> (optional)
1847 # A pointer to an associative array of labels to print next to each checkbox
1848 # in the form $label{'value'}="Long explanatory label".
1849 # Otherwise the provided values are used as the labels.
1851 # An ARRAY containing a series of <INPUT TYPE="radio"> fields
1853 'radio_group' => <<'END_OF_FUNC',
1855 my($self,@p) = self_or_default(@_);
1857 my($name,$values,$default,$linebreak,$labels,
1858 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
1859 $self->rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,
1860 ROWS,[COLUMNS,COLS],
1861 ROWHEADERS,COLHEADERS,
1862 [OVERRIDE,FORCE],NOLABELS],@p);
1863 my($result,$checked);
1865 if (!$override && defined($self->param($name))) {
1866 $checked = $self->param($name);
1868 $checked = $default;
1870 # If no check array is specified, check the first by default
1871 $checked = $values->[0] unless defined($checked) && $checked ne '';
1872 $name=$self->escapeHTML($name);
1874 my(@elements,@values);
1876 @values = $self->_set_values_and_labels($values,\$labels,$name);
1878 my($other) = @other ? " @other" : '';
1880 my($checkit) = $checked eq $_ ? ' CHECKED' : '';
1881 my($break) = $linebreak ? '<BR>' : '';
1883 unless (defined($nolabels) && $nolabels) {
1885 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1886 $label = $self->escapeHTML($label);
1888 $_=$self->escapeHTML($_);
1889 push(@elements,qq/<INPUT TYPE="radio" NAME="$name" VALUE="$_"$checkit$other>${label}${break}/);
1891 $self->register_parameter($name);
1892 return wantarray ? @elements : join(' ',@elements)
1893 unless defined($columns) || defined($rows);
1894 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1899 #### Method: popup_menu
1900 # Create a popup menu.
1902 # $name -> Name for all the menu
1903 # $values -> A pointer to a regular array containing the
1904 # text of each menu item.
1905 # $default -> (optional) Default item to display
1906 # $labels -> (optional)
1907 # A pointer to an associative array of labels to print next to each checkbox
1908 # in the form $label{'value'}="Long explanatory label".
1909 # Otherwise the provided values are used as the labels.
1911 # A string containing the definition of a popup menu.
1913 'popup_menu' => <<'END_OF_FUNC',
1915 my($self,@p) = self_or_default(@_);
1917 my($name,$values,$default,$labels,$override,@other) =
1918 $self->rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,[OVERRIDE,FORCE]],@p);
1919 my($result,$selected);
1921 if (!$override && defined($self->param($name))) {
1922 $selected = $self->param($name);
1924 $selected = $default;
1926 $name=$self->escapeHTML($name);
1927 my($other) = @other ? " @other" : '';
1930 @values = $self->_set_values_and_labels($values,\$labels,$name);
1932 $result = qq/<SELECT NAME="$name"$other>\n/;
1934 my($selectit) = defined($selected) ? ($selected eq $_ ? 'SELECTED' : '' ) : '';
1936 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1937 my($value) = $self->escapeHTML($_);
1938 $label=$self->escapeHTML($label);
1939 $result .= "<OPTION $selectit VALUE=\"$value\">$label\n";
1942 $result .= "</SELECT>\n";
1948 #### Method: scrolling_list
1949 # Create a scrolling list.
1951 # $name -> name for the list
1952 # $values -> A pointer to a regular array containing the
1953 # values for each option line in the list.
1954 # $defaults -> (optional)
1955 # 1. If a pointer to a regular array of options,
1956 # then this will be used to decide which
1957 # lines to turn on by default.
1958 # 2. Otherwise holds the value of the single line to turn on.
1959 # $size -> (optional) Size of the list.
1960 # $multiple -> (optional) If set, allow multiple selections.
1961 # $labels -> (optional)
1962 # A pointer to an associative array of labels to print next to each checkbox
1963 # in the form $label{'value'}="Long explanatory label".
1964 # Otherwise the provided values are used as the labels.
1966 # A string containing the definition of a scrolling list.
1968 'scrolling_list' => <<'END_OF_FUNC',
1969 sub scrolling_list {
1970 my($self,@p) = self_or_default(@_);
1971 my($name,$values,$defaults,$size,$multiple,$labels,$override,@other)
1972 = $self->rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1973 SIZE,MULTIPLE,LABELS,[OVERRIDE,FORCE]],@p);
1975 my($result,@values);
1976 @values = $self->_set_values_and_labels($values,\$labels,$name);
1978 $size = $size || scalar(@values);
1980 my(%selected) = $self->previous_or_default($name,$defaults,$override);
1981 my($is_multiple) = $multiple ? ' MULTIPLE' : '';
1982 my($has_size) = $size ? " SIZE=$size" : '';
1983 my($other) = @other ? " @other" : '';
1985 $name=$self->escapeHTML($name);
1986 $result = qq/<SELECT NAME="$name"$has_size$is_multiple$other>\n/;
1988 my($selectit) = $selected{$_} ? 'SELECTED' : '';
1990 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1991 $label=$self->escapeHTML($label);
1992 my($value)=$self->escapeHTML($_);
1993 $result .= "<OPTION $selectit VALUE=\"$value\">$label\n";
1995 $result .= "</SELECT>\n";
1996 $self->register_parameter($name);
2004 # $name -> Name of the hidden field
2005 # @default -> (optional) Initial values of field (may be an array)
2007 # $default->[initial values of field]
2009 # A string containing a <INPUT TYPE="hidden" NAME="name" VALUE="value">
2011 'hidden' => <<'END_OF_FUNC',
2013 my($self,@p) = self_or_default(@_);
2015 # this is the one place where we departed from our standard
2016 # calling scheme, so we have to special-case (darn)
2018 my($name,$default,$override,@other) =
2019 $self->rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2021 my $do_override = 0;
2022 if ( ref($p[0]) || substr($p[0],0,1) eq '-' || $self->use_named_parameters ) {
2023 @value = ref($default) ? @{$default} : $default;
2024 $do_override = $override;
2026 foreach ($default,$override,@other) {
2027 push(@value,$_) if defined($_);
2031 # use previous values if override is not set
2032 my @prev = $self->param($name);
2033 @value = @prev if !$do_override && @prev;
2035 $name=$self->escapeHTML($name);
2037 $_=$self->escapeHTML($_);
2038 push(@result,qq/<INPUT TYPE="hidden" NAME="$name" VALUE="$_">/);
2040 return wantarray ? @result : join('',@result);
2045 #### Method: image_button
2047 # $name -> Name of the button
2048 # $src -> URL of the image source
2049 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2051 # A string containing a <INPUT TYPE="image" NAME="name" SRC="url" ALIGN="alignment">
2053 'image_button' => <<'END_OF_FUNC',
2055 my($self,@p) = self_or_default(@_);
2057 my($name,$src,$alignment,@other) =
2058 $self->rearrange([NAME,SRC,ALIGN],@p);
2060 my($align) = $alignment ? " ALIGN=\U$alignment" : '';
2061 my($other) = @other ? " @other" : '';
2062 $name=$self->escapeHTML($name);
2063 return qq/<INPUT TYPE="image" NAME="$name" SRC="$src"$align$other>/;
2068 #### Method: self_url
2069 # Returns a URL containing the current script and all its
2070 # param/value pairs arranged as a query. You can use this
2071 # to create a link that, when selected, will reinvoke the
2072 # script with all its state information preserved.
2074 'self_url' => <<'END_OF_FUNC',
2076 my($self,@p) = self_or_default(@_);
2077 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2082 # This is provided as a synonym to self_url() for people unfortunate
2083 # enough to have incorporated it into their programs already!
2084 'state' => <<'END_OF_FUNC',
2092 # Like self_url, but doesn't return the query string part of
2095 'url' => <<'END_OF_FUNC',
2097 my($self,@p) = self_or_default(@_);
2098 my ($relative,$absolute,$full,$path_info,$query) =
2099 $self->rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING']],@p);
2101 $full++ if !($relative || $absolute);
2104 my $protocol = $self->protocol();
2105 $url = "$protocol://";
2106 my $vh = http('host');
2110 $url .= server_name();
2111 my $port = $self->server_port;
2113 unless (lc($protocol) eq 'http' && $port == 80)
2114 || (lc($protocol) eq 'https' && $port == 443);
2116 $url .= $self->script_name;
2117 } elsif ($relative) {
2118 ($url) = $self->script_name =~ m!([^/]+)$!;
2119 } elsif ($absolute) {
2120 $url = $self->script_name;
2122 $url .= $self->path_info if $path_info and $self->path_info;
2123 $url .= "?" . $self->query_string if $query and $self->query_string;
2130 # Set or read a cookie from the specified name.
2131 # Cookie can then be passed to header().
2132 # Usual rules apply to the stickiness of -value.
2134 # -name -> name for this cookie (optional)
2135 # -value -> value of this cookie (scalar, array or hash)
2136 # -path -> paths for which this cookie is valid (optional)
2137 # -domain -> internet domain in which this cookie is valid (optional)
2138 # -secure -> if true, cookie only passed through secure channel (optional)
2139 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2141 'cookie' => <<'END_OF_FUNC',
2143 my($self,@p) = self_or_default(@_);
2144 my($name,$value,$path,$domain,$secure,$expires) =
2145 $self->rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2147 require CGI::Cookie;
2149 # if no value is supplied, then we retrieve the
2150 # value of the cookie, if any. For efficiency, we cache the parsed
2151 # cookies in our state variables.
2152 unless ( defined($value) ) {
2153 $self->{'.cookies'} = CGI::Cookie->fetch
2154 unless $self->{'.cookies'};
2156 # If no name is supplied, then retrieve the names of all our cookies.
2157 return () unless $self->{'.cookies'};
2158 return keys %{$self->{'.cookies'}} unless $name;
2159 return () unless $self->{'.cookies'}->{$name};
2160 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2163 # If we get here, we're creating a new cookie
2164 return undef unless $name; # this is an error
2167 push(@param,'-name'=>$name);
2168 push(@param,'-value'=>$value);
2169 push(@param,'-domain'=>$domain) if $domain;
2170 push(@param,'-path'=>$path) if $path;
2171 push(@param,'-expires'=>$expires) if $expires;
2172 push(@param,'-secure'=>$secure) if $secure;
2174 return new CGI::Cookie(@param);
2178 # This internal routine creates an expires time exactly some number of
2179 # hours from the current time. It incorporates modifications from
2181 'expire_calc' => <<'END_OF_FUNC',
2184 my(%mult) = ('s'=>1,
2190 # format for time can be in any of the forms...
2191 # "now" -- expire immediately
2192 # "+180s" -- in 180 seconds
2193 # "+2m" -- in 2 minutes
2194 # "+12h" -- in 12 hours
2196 # "+3M" -- in 3 months
2197 # "+2y" -- in 2 years
2198 # "-3m" -- 3 minutes ago(!)
2199 # If you don't supply one of these forms, we assume you are
2200 # specifying the date yourself
2202 if (!$time || (lc($time) eq 'now')) {
2204 } elsif ($time=~/^([+-]?(?:\d+|\d*\.\d*))([mhdMy]?)/) {
2205 $offset = ($mult{$2} || 1)*$1;
2209 return (time+$offset);
2213 # This internal routine creates date strings suitable for use in
2214 # cookies and HTTP headers. (They differ, unfortunately.)
2215 # Thanks to Fisher Mark for this.
2216 'expires' => <<'END_OF_FUNC',
2218 my($time,$format) = @_;
2221 my(@MON)=qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
2222 my(@WDAY) = qw/Sun Mon Tue Wed Thu Fri Sat/;
2224 # pass through preformatted dates for the sake of expire_calc()
2225 $time = expire_calc($time);
2226 return $time unless $time =~ /^\d+$/;
2228 # make HTTP/cookie date string from GMT'ed time
2229 # (cookies use '-' as date separator, HTTP uses ' ')
2231 $sc = '-' if $format eq "cookie";
2232 my($sec,$min,$hour,$mday,$mon,$year,$wday) = gmtime($time);
2234 return sprintf("%s, %02d$sc%s$sc%04d %02d:%02d:%02d GMT",
2235 $WDAY[$wday],$mday,$MON[$mon],$year,$hour,$min,$sec);
2239 'parse_keywordlist' => <<'END_OF_FUNC',
2240 sub parse_keywordlist {
2241 my($self,$tosplit) = @_;
2242 $tosplit = unescape($tosplit); # unescape the keywords
2243 $tosplit=~tr/+/ /; # pluses to spaces
2244 my(@keywords) = split(/\s+/,$tosplit);
2249 'param_fetch' => <<'END_OF_FUNC',
2251 my($self,@p) = self_or_default(@_);
2252 my($name) = $self->rearrange([NAME],@p);
2253 unless (exists($self->{$name})) {
2254 $self->add_parameter($name);
2255 $self->{$name} = [];
2258 return $self->{$name};
2262 ###############################################
2263 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2264 ###############################################
2266 #### Method: path_info
2267 # Return the extra virtual path information provided
2268 # after the URL (if any)
2270 'path_info' => <<'END_OF_FUNC',
2272 my ($self,$info) = self_or_default(@_);
2273 if (defined($info)) {
2274 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2275 $self->{'.path_info'} = $info;
2276 } elsif (! defined($self->{'.path_info'}) ) {
2277 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2278 $ENV{'PATH_INFO'} : '';
2280 # hack to fix broken path info in IIS
2281 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2284 return $self->{'.path_info'};
2289 #### Method: request_method
2290 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2292 'request_method' => <<'END_OF_FUNC',
2293 sub request_method {
2294 return $ENV{'REQUEST_METHOD'};
2298 #### Method: path_translated
2299 # Return the physical path information provided
2300 # by the URL (if any)
2302 'path_translated' => <<'END_OF_FUNC',
2303 sub path_translated {
2304 return $ENV{'PATH_TRANSLATED'};
2309 #### Method: query_string
2310 # Synthesize a query string from our current
2313 'query_string' => <<'END_OF_FUNC',
2315 my($self) = self_or_default(@_);
2316 my($param,$value,@pairs);
2317 foreach $param ($self->param) {
2318 my($eparam) = escape($param);
2319 foreach $value ($self->param($param)) {
2320 $value = escape($value);
2321 push(@pairs,"$eparam=$value");
2324 return join("&",@pairs);
2330 # Without parameters, returns an array of the
2331 # MIME types the browser accepts.
2332 # With a single parameter equal to a MIME
2333 # type, will return undef if the browser won't
2334 # accept it, 1 if the browser accepts it but
2335 # doesn't give a preference, or a floating point
2336 # value between 0.0 and 1.0 if the browser
2337 # declares a quantitative score for it.
2338 # This handles MIME type globs correctly.
2340 'accept' => <<'END_OF_FUNC',
2342 my($self,$search) = self_or_CGI(@_);
2343 my(%prefs,$type,$pref,$pat);
2345 my(@accept) = split(',',$self->http('accept'));
2348 ($pref) = /q=(\d\.\d+|\d+)/;
2349 ($type) = m#(\S+/[^;]+)#;
2351 $prefs{$type}=$pref || 1;
2354 return keys %prefs unless $search;
2356 # if a search type is provided, we may need to
2357 # perform a pattern matching operation.
2358 # The MIME types use a glob mechanism, which
2359 # is easily translated into a perl pattern match
2361 # First return the preference for directly supported
2363 return $prefs{$search} if $prefs{$search};
2365 # Didn't get it, so try pattern matching.
2366 foreach (keys %prefs) {
2367 next unless /\*/; # not a pattern match
2368 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2369 $pat =~ s/\*/.*/g; # turn it into a pattern
2370 return $prefs{$_} if $search=~/$pat/;
2376 #### Method: user_agent
2377 # If called with no parameters, returns the user agent.
2378 # If called with one parameter, does a pattern match (case
2379 # insensitive) on the user agent.
2381 'user_agent' => <<'END_OF_FUNC',
2383 my($self,$match)=self_or_CGI(@_);
2384 return $self->http('user_agent') unless $match;
2385 return $self->http('user_agent') =~ /$match/i;
2390 #### Method: raw_cookie
2391 # Returns the magic cookies for the session.
2392 # The cookies are not parsed or altered in any way, i.e.
2393 # cookies are returned exactly as given in the HTTP
2394 # headers. If a cookie name is given, only that cookie's
2395 # value is returned, otherwise the entire raw cookie
2398 'raw_cookie' => <<'END_OF_FUNC',
2400 my($self,$key) = self_or_CGI(@_);
2402 require CGI::Cookie;
2404 if (defined($key)) {
2405 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2406 unless $self->{'.raw_cookies'};
2408 return () unless $self->{'.raw_cookies'};
2409 return () unless $self->{'.raw_cookies'}->{$key};
2410 return $self->{'.raw_cookies'}->{$key};
2412 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2416 #### Method: virtual_host
2417 # Return the name of the virtual_host, which
2418 # is not always the same as the server
2420 'virtual_host' => <<'END_OF_FUNC',
2422 my $vh = http('host') || server_name();
2423 $vh =~ s/:\d+$//; # get rid of port number
2428 #### Method: remote_host
2429 # Return the name of the remote host, or its IP
2430 # address if unavailable. If this variable isn't
2431 # defined, it returns "localhost" for debugging
2434 'remote_host' => <<'END_OF_FUNC',
2436 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2442 #### Method: remote_addr
2443 # Return the IP addr of the remote host.
2445 'remote_addr' => <<'END_OF_FUNC',
2447 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2452 #### Method: script_name
2453 # Return the partial URL to this script for
2454 # self-referencing scripts. Also see
2455 # self_url(), which returns a URL with all state information
2458 'script_name' => <<'END_OF_FUNC',
2460 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2461 # These are for debugging
2462 return "/$0" unless $0=~/^\//;
2468 #### Method: referer
2469 # Return the HTTP_REFERER: useful for generating
2472 'referer' => <<'END_OF_FUNC',
2474 my($self) = self_or_CGI(@_);
2475 return $self->http('referer');
2480 #### Method: server_name
2481 # Return the name of the server
2483 'server_name' => <<'END_OF_FUNC',
2485 return $ENV{'SERVER_NAME'} || 'localhost';
2489 #### Method: server_software
2490 # Return the name of the server software
2492 'server_software' => <<'END_OF_FUNC',
2493 sub server_software {
2494 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2498 #### Method: server_port
2499 # Return the tcp/ip port the server is running on
2501 'server_port' => <<'END_OF_FUNC',
2503 return $ENV{'SERVER_PORT'} || 80; # for debugging
2507 #### Method: server_protocol
2508 # Return the protocol (usually HTTP/1.0)
2510 'server_protocol' => <<'END_OF_FUNC',
2511 sub server_protocol {
2512 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2517 # Return the value of an HTTP variable, or
2518 # the list of variables if none provided
2520 'http' => <<'END_OF_FUNC',
2522 my ($self,$parameter) = self_or_CGI(@_);
2523 return $ENV{$parameter} if $parameter=~/^HTTP/;
2524 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2526 foreach (keys %ENV) {
2527 push(@p,$_) if /^HTTP/;
2534 # Return the value of HTTPS
2536 'https' => <<'END_OF_FUNC',
2539 my ($self,$parameter) = self_or_CGI(@_);
2540 return $ENV{HTTPS} unless $parameter;
2541 return $ENV{$parameter} if $parameter=~/^HTTPS/;
2542 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2544 foreach (keys %ENV) {
2545 push(@p,$_) if /^HTTPS/;
2551 #### Method: protocol
2552 # Return the protocol (http or https currently)
2554 'protocol' => <<'END_OF_FUNC',
2558 return 'https' if uc($self->https()) eq 'ON';
2559 return 'https' if $self->server_port == 443;
2560 my $prot = $self->server_protocol;
2561 my($protocol,$version) = split('/',$prot);
2562 return "\L$protocol\E";
2566 #### Method: remote_ident
2567 # Return the identity of the remote user
2568 # (but only if his host is running identd)
2570 'remote_ident' => <<'END_OF_FUNC',
2572 return $ENV{'REMOTE_IDENT'};
2577 #### Method: auth_type
2578 # Return the type of use verification/authorization in use, if any.
2580 'auth_type' => <<'END_OF_FUNC',
2582 return $ENV{'AUTH_TYPE'};
2587 #### Method: remote_user
2588 # Return the authorization name used for user
2591 'remote_user' => <<'END_OF_FUNC',
2593 return $ENV{'REMOTE_USER'};
2598 #### Method: user_name
2599 # Try to return the remote user's name by hook or by
2602 'user_name' => <<'END_OF_FUNC',
2604 my ($self) = self_or_CGI(@_);
2605 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2610 # Set or return the NPH global flag
2612 'nph' => <<'END_OF_FUNC',
2614 my ($self,$param) = self_or_CGI(@_);
2615 $CGI::NPH = $param if defined($param);
2620 #### Method: private_tempfiles
2621 # Set or return the private_tempfiles global flag
2623 'private_tempfiles' => <<'END_OF_FUNC',
2624 sub private_tempfiles {
2625 my ($self,$param) = self_or_CGI(@_);
2626 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
2627 return $CGI::PRIVATE_TEMPFILES;
2631 #### Method: default_dtd
2632 # Set or return the default_dtd global
2634 'default_dtd' => <<'END_OF_FUNC',
2636 my ($self,$param) = self_or_CGI(@_);
2637 $CGI::DEFAULT_DTD = $param if defined($param);
2638 return $CGI::DEFAULT_DTD;
2642 # -------------- really private subroutines -----------------
2643 'previous_or_default' => <<'END_OF_FUNC',
2644 sub previous_or_default {
2645 my($self,$name,$defaults,$override) = @_;
2648 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2649 defined($self->param($name)) ) ) {
2650 grep($selected{$_}++,$self->param($name));
2651 } elsif (defined($defaults) && ref($defaults) &&
2652 (ref($defaults) eq 'ARRAY')) {
2653 grep($selected{$_}++,@{$defaults});
2655 $selected{$defaults}++ if defined($defaults);
2662 'register_parameter' => <<'END_OF_FUNC',
2663 sub register_parameter {
2664 my($self,$param) = @_;
2665 $self->{'.parametersToAdd'}->{$param}++;
2669 'get_fields' => <<'END_OF_FUNC',
2672 return $self->CGI::hidden('-name'=>'.cgifields',
2673 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2678 'read_from_cmdline' => <<'END_OF_FUNC',
2679 sub read_from_cmdline {
2685 require "shellwords.pl";
2686 print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2687 chomp(@lines = <STDIN>); # remove newlines
2688 $input = join(" ",@lines);
2689 @words = &shellwords($input);
2696 if ("@words"=~/=/) {
2697 $query_string = join('&',@words);
2699 $query_string = join('+',@words);
2701 return $query_string;
2706 # subroutine: read_multipart
2708 # Read multipart data and store it into our parameters.
2709 # An interesting feature is that if any of the parts is a file, we
2710 # create a temporary file and open up a filehandle on it so that the
2711 # caller can read from it if necessary.
2713 'read_multipart' => <<'END_OF_FUNC',
2714 sub read_multipart {
2715 my($self,$boundary,$length,$filehandle) = @_;
2716 my($buffer) = $self->new_MultipartBuffer($boundary,$length,$filehandle);
2717 return unless $buffer;
2720 while (!$buffer->eof) {
2721 %header = $buffer->readHeader;
2722 die "Malformed multipart POST\n" unless %header;
2724 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
2726 # Bug: Netscape doesn't escape quotation marks in file names!!!
2727 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\";]*)"?/;
2729 # add this parameter to our list
2730 $self->add_parameter($param);
2732 # If no filename specified, then just read the data and assign it
2733 # to our parameter list.
2734 unless ($filename) {
2735 my($value) = $buffer->readBody;
2736 push(@{$self->{$param}},$value);
2740 my ($tmpfile,$tmp,$filehandle);
2742 # If we get here, then we are dealing with a potentially large
2743 # uploaded form. Save the data to a temporary file, then open
2744 # the file for reading.
2746 # skip the file if uploads disabled
2747 if ($DISABLE_UPLOADS) {
2748 while (defined($data = $buffer->read)) { }
2752 $tmpfile = new TempFile;
2753 $tmp = $tmpfile->as_string;
2755 $filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES);
2757 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2758 chmod 0600,$tmp; # only the owner can tamper with it
2761 while (defined($data = $buffer->read)) {
2762 print $filehandle $data;
2765 # back up to beginning of file
2766 seek($filehandle,0,0);
2767 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2769 # Save some information about the uploaded file where we can get
2771 $self->{'.tmpfiles'}->{$filename}= {
2775 push(@{$self->{$param}},$filehandle);
2781 'tmpFileName' => <<'END_OF_FUNC',
2783 my($self,$filename) = self_or_default(@_);
2784 return $self->{'.tmpfiles'}->{$filename}->{name} ?
2785 $self->{'.tmpfiles'}->{$filename}->{name}->as_string
2790 'uploadInfo' => <<'END_OF_FUNC',
2792 my($self,$filename) = self_or_default(@_);
2793 return $self->{'.tmpfiles'}->{$filename}->{info};
2797 # internal routine, don't use
2798 '_set_values_and_labels' => <<'END_OF_FUNC',
2799 sub _set_values_and_labels {
2802 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
2803 return $self->param($n) if !defined($v);
2804 return $v if !ref($v);
2805 return ref($v) eq 'HASH' ? keys %$v : @$v;
2809 '_compile_all' => <<'END_OF_FUNC',
2812 next if defined(&$_);
2813 $AUTOLOAD = "CGI::$_";
2823 #########################################################
2824 # Globals and stubs for other packages that we use.
2825 #########################################################
2827 ################### Fh -- lightweight filehandle ###############
2836 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
2838 $AUTOLOADED_ROUTINES = ''; # prevent -w error
2839 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2841 'asString' => <<'END_OF_FUNC',
2845 $i=~ s/^\*(\w+::)+//; # get rid of package name
2851 'compare' => <<'END_OF_FUNC',
2855 return "$self" cmp $value;
2859 'new' => <<'END_OF_FUNC',
2861 my($pack,$name,$file,$delete) = @_;
2862 require Fcntl unless defined &Fcntl::O_RDWR;
2864 *{$FH} = quotemeta($name);
2865 sysopen($FH,$file,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL())
2866 || die "CGI open of $file: $!\n";
2867 unlink($file) if $delete;
2868 return bless \*{$FH},$pack;
2872 'DESTROY' => <<'END_OF_FUNC',
2882 ######################## MultipartBuffer ####################
2883 package MultipartBuffer;
2885 # how many bytes to read at a time. We use
2886 # a 5K buffer by default.
2887 $INITIAL_FILLUNIT = 1024 * 5;
2888 $TIMEOUT = 10*60; # 10 minute timeout
2889 $SPIN_LOOP_MAX = 1000; # bug fix for some Netscape servers
2892 #reuse the autoload function
2893 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
2895 # avoid autoloader warnings
2898 ###############################################################################
2899 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
2900 ###############################################################################
2901 $AUTOLOADED_ROUTINES = ''; # prevent -w error
2902 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
2905 'new' => <<'END_OF_FUNC',
2907 my($package,$interface,$boundary,$length,$filehandle) = @_;
2908 $FILLUNIT = $INITIAL_FILLUNIT;
2911 my($package) = caller;
2912 # force into caller's package if necessary
2913 $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
2915 $IN = "main::STDIN" unless $IN;
2917 $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
2919 # If the user types garbage into the file upload field,
2920 # then Netscape passes NOTHING to the server (not good).
2921 # We may hang on this read in that case. So we implement
2922 # a read timeout. If nothing is ready to read
2923 # by then, we return.
2925 # Netscape seems to be a little bit unreliable
2926 # about providing boundary strings.
2929 # Under the MIME spec, the boundary consists of the
2930 # characters "--" PLUS the Boundary string
2932 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
2933 # the two extra spaces. We do a special case here on the user-agent!!!!
2934 $boundary = "--$boundary" unless CGI::user_agent('MSIE 3\.0[12]; Mac');
2936 } else { # otherwise we find it ourselves
2938 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
2939 $boundary = <$IN>; # BUG: This won't work correctly under mod_perl
2940 $length -= length($boundary);
2941 chomp($boundary); # remove the CRLF
2942 $/ = $old; # restore old line separator
2945 my $self = {LENGTH=>$length,
2946 BOUNDARY=>$boundary,
2948 INTERFACE=>$interface,
2952 $FILLUNIT = length($boundary)
2953 if length($boundary) > $FILLUNIT;
2955 my $retval = bless $self,ref $package || $package;
2957 # Read the preamble and the topmost (boundary) line plus the CRLF.
2958 while ($self->read(0)) { }
2959 die "Malformed multipart POST\n" if $self->eof;
2965 'readHeader' => <<'END_OF_FUNC',
2972 if ($CGI::OS eq 'VMS') { # tssk, tssk: inconsistency alert!
2973 local($CRLF) = "\015\012";
2977 $self->fillBuffer($FILLUNIT);
2978 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
2979 $ok++ if $self->{BUFFER} eq '';
2980 $bad++ if !$ok && $self->{LENGTH} <= 0;
2981 # this was a bad idea
2982 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
2983 } until $ok || $bad;
2986 my($header) = substr($self->{BUFFER},0,$end+2);
2987 substr($self->{BUFFER},0,$end+4) = '';
2991 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
2992 # (Folding Long Header Fields), 3.4.3 (Comments)
2993 # and 3.4.5 (Quoted-Strings).
2995 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
2996 $header=~s/$CRLF\s+/ /og; # merge continuation lines
2997 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
2998 my ($field_name,$field_value) = ($1,$2); # avoid taintedness
2999 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3000 $return{$field_name}=$field_value;
3006 # This reads and returns the body as a single scalar value.
3007 'readBody' => <<'END_OF_FUNC',
3012 while (defined($data = $self->read)) {
3013 $returnval .= $data;
3019 # This will read $bytes or until the boundary is hit, whichever happens
3020 # first. After the boundary is hit, we return undef. The next read will
3021 # skip over the boundary and begin reading again;
3022 'read' => <<'END_OF_FUNC',
3024 my($self,$bytes) = @_;
3026 # default number of bytes to read
3027 $bytes = $bytes || $FILLUNIT;
3029 # Fill up our internal buffer in such a way that the boundary
3030 # is never split between reads.
3031 $self->fillBuffer($bytes);
3033 # Find the boundary in the buffer (it may not be there).
3034 my $start = index($self->{BUFFER},$self->{BOUNDARY});
3035 # protect against malformed multipart POST operations
3036 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3038 # If the boundary begins the data, then skip past it
3039 # and return undef. The +2 here is a fiendish plot to
3040 # remove the CR/LF pair at the end of the boundary.
3043 # clear us out completely if we've hit the last boundary.
3044 if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
3050 # just remove the boundary.
3051 substr($self->{BUFFER},0,length($self->{BOUNDARY})+2)='';
3056 if ($start > 0) { # read up to the boundary
3057 $bytesToReturn = $start > $bytes ? $bytes : $start;
3058 } else { # read the requested number of bytes
3059 # leave enough bytes in the buffer to allow us to read
3060 # the boundary. Thanks to Kevin Hendrick for finding
3062 $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
3065 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3066 substr($self->{BUFFER},0,$bytesToReturn)='';
3068 # If we hit the boundary, remove the CRLF from the end.
3069 return ($start > 0) ? substr($returnval,0,-2) : $returnval;
3074 # This fills up our internal buffer in such a way that the
3075 # boundary is never split between reads
3076 'fillBuffer' => <<'END_OF_FUNC',
3078 my($self,$bytes) = @_;
3079 return unless $self->{LENGTH};
3081 my($boundaryLength) = length($self->{BOUNDARY});
3082 my($bufferLength) = length($self->{BUFFER});
3083 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3084 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3086 # Try to read some data. We may hang here if the browser is screwed up.
3087 my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
3092 # An apparent bug in the Apache server causes the read()
3093 # to return zero bytes repeatedly without blocking if the
3094 # remote user aborts during a file transfer. I don't know how
3095 # they manage this, but the workaround is to abort if we get
3096 # more than SPIN_LOOP_MAX consecutive zero reads.
3097 if ($bytesRead == 0) {
3098 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3099 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3101 $self->{ZERO_LOOP_COUNTER}=0;
3104 $self->{LENGTH} -= $bytesRead;
3109 # Return true when we've finished reading
3110 'eof' => <<'END_OF_FUNC'
3113 return 1 if (length($self->{BUFFER}) == 0)
3114 && ($self->{LENGTH} <= 0);
3122 ####################################################################################
3123 ################################## TEMPORARY FILES #################################
3124 ####################################################################################
3128 $MAC = $CGI::OS eq 'MACINTOSH';
3129 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3130 unless ($TMPDIRECTORY) {
3131 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3132 "${SL}tmp","${SL}temp","${vol}${SL}Temporary Items",
3135 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3139 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3143 # cute feature, but overload implementation broke it
3144 # %OVERLOAD = ('""'=>'as_string');
3145 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3147 ###############################################################################
3148 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3149 ###############################################################################
3150 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3151 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3154 'new' => <<'END_OF_FUNC',
3159 for ($i = 0; $i < $MAXTRIES; $i++) {
3160 $directory = sprintf("${TMPDIRECTORY}${SL}CGItemp%d%04d",${$},++$SEQUENCE);
3161 last if ! -f $directory;
3163 return bless \$directory;
3167 'DESTROY' => <<'END_OF_FUNC',
3170 unlink $$self; # get rid of the file
3174 'as_string' => <<'END_OF_FUNC'
3186 # We get a whole bunch of warnings about "possibly uninitialized variables"
3187 # when running with the -w switch. Touch them all once to get rid of the
3188 # warnings. This is ugly and I hate it.
3193 $MultipartBuffer::SPIN_LOOP_MAX;
3194 $MultipartBuffer::CRLF;
3195 $MultipartBuffer::TIMEOUT;
3196 $MultipartBuffer::INITIAL_FILLUNIT;
3197 $TempFile::SEQUENCE;
3208 CGI - Simple Common Gateway Interface Class
3212 # CGI script that creates a fill-out form
3213 # and echoes back its values.
3215 use CGI qw/:standard/;
3217 start_html('A Simple Example'),
3218 h1('A Simple Example'),
3220 "What's your name? ",textfield('name'),p,
3221 "What's the combination?", p,
3222 checkbox_group(-name=>'words',
3223 -values=>['eenie','meenie','minie','moe'],
3224 -defaults=>['eenie','minie']), p,
3225 "What's your favorite color? ",
3226 popup_menu(-name=>'color',
3227 -values=>['red','green','blue','chartreuse']),p,
3233 print "Your name is",em(param('name')),p,
3234 "The keywords are: ",em(join(", ",param('words'))),p,
3235 "Your favorite color is ",em(param('color')),
3241 This perl library uses perl5 objects to make it easy to create Web
3242 fill-out forms and parse their contents. This package defines CGI
3243 objects, entities that contain the values of the current query string
3244 and other state variables. Using a CGI object's methods, you can
3245 examine keywords and parameters passed to your script, and create
3246 forms whose initial values are taken from the current query (thereby
3247 preserving state information). The module provides shortcut functions
3248 that produce boilerplate HTML, reducing typing and coding errors. It
3249 also provides functionality for some of the more advanced features of
3250 CGI scripting, including support for file uploads, cookies, cascading
3251 style sheets, server push, and frames.
3253 CGI.pm also provides a simple function-oriented programming style for
3254 those who don't need its object-oriented features.
3256 The current version of CGI.pm is available at
3258 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3259 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3263 =head2 PROGRAMMING STYLE
3265 There are two styles of programming with CGI.pm, an object-oriented
3266 style and a function-oriented style. In the object-oriented style you
3267 create one or more CGI objects and then use object methods to create
3268 the various elements of the page. Each CGI object starts out with the
3269 list of named parameters that were passed to your CGI script by the
3270 server. You can modify the objects, save them to a file or database
3271 and recreate them. Because each object corresponds to the "state" of
3272 the CGI script, and because each object's parameter list is
3273 independent of the others, this allows you to save the state of the
3274 script and restore it later.
3276 For example, using the object oriented style, here is now you create
3277 a simple "Hello World" HTML page:
3279 #!/usr/local/bin/pelr
3280 use CGI; # load CGI routines
3281 $q = new CGI; # create new CGI object
3282 print $q->header, # create the HTTP header
3283 $q->start_html('hello world'), # start the HTML
3284 $q->h1('hello world'), # level 1 header
3285 $q->end_html; # end the HTML
3287 In the function-oriented style, there is one default CGI object that
3288 you rarely deal with directly. Instead you just call functions to
3289 retrieve CGI parameters, create HTML tags, manage cookies, and so
3290 on. This provides you with a cleaner programming interface, but
3291 limits you to using one CGI object at a time. The following example
3292 prints the same page, but uses the function-oriented interface.
3293 The main differences are that we now need to import a set of functions
3294 into our name space (usually the "standard" functions), and we don't
3295 need to create the CGI object.
3297 #!/usr/local/bin/pelr
3298 use CGI qw/:standard/; # load standard CGI routines
3299 print header, # create the HTTP header
3300 start_html('hello world'), # start the HTML
3301 h1('hello world'), # level 1 header
3302 end_html; # end the HTML
3304 The examples in this document mainly use the object-oriented style.
3305 See HOW TO IMPORT FUNCTIONS for important information on
3306 function-oriented programming in CGI.pm
3308 =head2 CALLING CGI.PM ROUTINES
3310 Most CGI.pm routines accept several arguments, sometimes as many as 20
3311 optional ones! To simplify this interface, all routines use a named
3312 argument calling style that looks like this:
3314 print $q->header(-type=>'image/gif',-expires=>'+3d');
3316 Each argument name is preceded by a dash. Neither case nor order
3317 matters in the argument list. -type, -Type, and -TYPE are all
3318 acceptable. In fact, only the first argument needs to begin with a
3319 dash. If a dash is present in the first argument, CGI.pm assumes
3320 dashes for the subsequent ones.
3322 You don't have to use the hyphen at allif you don't want to. After
3323 creating a CGI object, call the B<use_named_parameters()> method with
3324 a nonzero value. This will tell CGI.pm that you intend to use named
3325 parameters exclusively:
3328 $query->use_named_parameters(1);
3329 $field = $query->radio_group('name'=>'OS',
3330 'values'=>['Unix','Windows','Macintosh'],
3333 Several routines are commonly called with just one argument. In the
3334 case of these routines you can provide the single argument without an
3335 argument name. header() happens to be one of these routines. In this
3336 case, the single argument is the document type.
3338 print $q->header('text/html');
3340 Other such routines are documented below.
3342 Sometimes named arguments expect a scalar, sometimes a reference to an
3343 array, and sometimes a reference to a hash. Often, you can pass any
3344 type of argument and the routine will do whatever is most appropriate.
3345 For example, the param() routine is used to set a CGI parameter to a
3346 single or a multi-valued value. The two cases are shown below:
3348 $q->param(-name=>'veggie',-value=>'tomato');
3349 $q->param(-name=>'veggie',-value=>'[tomato','tomahto','potato','potahto']);
3351 A large number of routines in CGI.pm actually aren't specifically
3352 defined in the module, but are generated automatically as needed.
3353 These are the "HTML shortcuts," routines that generate HTML tags for
3354 use in dynamically-generated pages. HTML tags have both attributes
3355 (the attribute="value" pairs within the tag itself) and contents (the
3356 part between the opening and closing pairs.) To distinguish between
3357 attributes and contents, CGI.pm uses the convention of passing HTML
3358 attributes as a hash reference as the first argument, and the
3359 contents, if any, as any subsequent arguments. It works out like
3365 h1('some','contents'); <H1>some contents</H1>
3366 h1({-align=>left}); <H1 ALIGN="LEFT">
3367 h1({-align=>left},'contents'); <H1 ALIGN="LEFT">contents</H1>
3369 HTML tags are described in more detail later.
3371 Many newcomers to CGI.pm are puzzled by the difference between the
3372 calling conventions for the HTML shortcuts, which require curly braces
3373 around the HTML tag attributes, and the calling conventions for other
3374 routines, which manage to generate attributes without the curly
3375 brackets. Don't be confused. As a convenience the curly braces are
3376 optional in all but the HTML shortcuts. If you like, you can use
3377 curly braces when calling any routine that takes named arguments. For
3380 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3382 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3383 names conflict with built-in Perl functions. The most frequent of
3384 these is the -values argument, used to create multi-valued menus,
3385 radio button clusters and the like. To get around this warning, you
3386 have several choices:
3390 =item 1. Use another name for the argument, if one is available. For
3391 example, -value is an alias for -values.
3393 =item 2. Change the capitalization, e.g. -Values
3395 =item 3. Put quotes around the argument name, e.g. '-values'
3399 Many routines will do something useful with a named argument that it
3400 doesn't recognize. For example, you can produce non-standard HTTP
3401 header fields by providing them as named arguments:
3403 print $q->header(-type => 'text/html',
3404 -cost => 'Three smackers',
3405 -annoyance_level => 'high',
3406 -complaints_to => 'bit bucket');
3408 This will produce the following nonstandard HTTP header:
3411 Cost: Three smackers
3412 Annoyance-level: high
3413 Complaints-to: bit bucket
3414 Content-type: text/html
3416 Notice the way that underscores are translated automatically into
3417 hyphens. HTML-generating routines perform a different type of
3420 This feature allows you to keep up with the rapidly changing HTTP and
3423 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
3427 This will parse the input (from both POST and GET methods) and store
3428 it into a perl5 object called $query.
3430 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
3432 $query = new CGI(INPUTFILE);
3434 If you provide a file handle to the new() method, it will read
3435 parameters from the file (or STDIN, or whatever). The file can be in
3436 any of the forms describing below under debugging (i.e. a series of
3437 newline delimited TAG=VALUE pairs will work). Conveniently, this type
3438 of file is created by the save() method (see below). Multiple records
3439 can be saved and restored.
3441 Perl purists will be pleased to know that this syntax accepts
3442 references to file handles, or even references to filehandle globs,
3443 which is the "official" way to pass a filehandle:
3445 $query = new CGI(\*STDIN);
3447 You can also initialize the CGI object with a FileHandle or IO::File
3450 If you are using the function-oriented interface and want to
3451 initialize CGI state from a file handle, the way to do this is with
3452 B<restore_parameters()>. This will (re)initialize the
3453 default CGI object from the indicated file handle.
3455 open (IN,"test.in") || die;
3456 restore_parameters(IN);
3459 You can also initialize the query object from an associative array
3462 $query = new CGI( {'dinosaur'=>'barney',
3463 'song'=>'I love you',
3464 'friends'=>[qw/Jessica George Nancy/]}
3467 or from a properly formatted, URL-escaped query string:
3469 $query = new CGI('dinosaur=barney&color=purple');
3471 or from a previously existing CGI object (currently this clones the
3472 parameter list, but none of the other object-specific fields, such as
3475 $old_query = new CGI;
3476 $new_query = new CGI($old_query);
3478 To create an empty query, initialize it from an empty string or hash:
3480 $empty_query = new CGI("");
3484 $empty_query = new CGI({});
3486 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
3488 @keywords = $query->keywords
3490 If the script was invoked as the result of an <ISINDEX> search, the
3491 parsed keywords can be obtained as an array using the keywords() method.
3493 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
3495 @names = $query->param
3497 If the script was invoked with a parameter list
3498 (e.g. "name1=value1&name2=value2&name3=value3"), the param()
3499 method will return the parameter names as a list. If the
3500 script was invoked as an <ISINDEX> script, there will be a
3501 single parameter named 'keywords'.
3503 NOTE: As of version 1.5, the array of parameter names returned will
3504 be in the same order as they were submitted by the browser.
3505 Usually this order is the same as the order in which the
3506 parameters are defined in the form (however, this isn't part
3507 of the spec, and so isn't guaranteed).
3509 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
3511 @values = $query->param('foo');
3515 $value = $query->param('foo');
3517 Pass the param() method a single argument to fetch the value of the
3518 named parameter. If the parameter is multivalued (e.g. from multiple
3519 selections in a scrolling list), you can ask to receive an array. Otherwise
3520 the method will return a single value.
3522 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
3524 $query->param('foo','an','array','of','values');
3526 This sets the value for the named parameter 'foo' to an array of
3527 values. This is one way to change the value of a field AFTER
3528 the script has been invoked once before. (Another way is with
3529 the -override parameter accepted by all methods that generate
3532 param() also recognizes a named parameter style of calling described
3533 in more detail later:
3535 $query->param(-name=>'foo',-values=>['an','array','of','values']);
3539 $query->param(-name=>'foo',-value=>'the value');
3541 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
3543 $query->append(-name=>'foo',-values=>['yet','more','values']);
3545 This adds a value or list of values to the named parameter. The
3546 values are appended to the end of the parameter if it already exists.
3547 Otherwise the parameter is created. Note that this method only
3548 recognizes the named argument calling syntax.
3550 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
3552 $query->import_names('R');
3554 This creates a series of variables in the 'R' namespace. For example,
3555 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
3556 If no namespace is given, this method will assume 'Q'.
3557 WARNING: don't import anything into 'main'; this is a major security
3560 In older versions, this method was called B<import()>. As of version 2.20,
3561 this name has been removed completely to avoid conflict with the built-in
3562 Perl module B<import> operator.
3564 =head2 DELETING A PARAMETER COMPLETELY:
3566 $query->delete('foo');
3568 This completely clears a parameter. It sometimes useful for
3569 resetting parameters that you don't want passed down between
3572 If you are using the function call interface, use "Delete()" instead
3573 to avoid conflicts with Perl's built-in delete operator.
3575 =head2 DELETING ALL PARAMETERS:
3577 $query->delete_all();
3579 This clears the CGI object completely. It might be useful to ensure
3580 that all the defaults are taken when you create a fill-out form.
3582 Use Delete_all() instead if you are using the function call interface.
3584 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
3586 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
3587 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
3589 If you need access to the parameter list in a way that isn't covered
3590 by the methods above, you can obtain a direct reference to it by
3591 calling the B<param_fetch()> method with the name of the . This
3592 will return an array reference to the named parameters, which you then
3593 can manipulate in any way you like.
3595 You can also use a named argument style using the B<-name> argument.
3597 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
3599 $query->save(FILEHANDLE)
3601 This will write the current state of the form to the provided
3602 filehandle. You can read it back in by providing a filehandle
3603 to the new() method. Note that the filehandle can be a file, a pipe,
3606 The format of the saved file is:
3614 Both name and value are URL escaped. Multi-valued CGI parameters are
3615 represented as repeated names. A session record is delimited by a
3616 single = symbol. You can write out multiple records and read them
3617 back in with several calls to B<new>. You can do this across several
3618 sessions by opening the file in append mode, allowing you to create
3619 primitive guest books, or to keep a history of users' queries. Here's
3620 a short example of creating multiple session records:
3624 open (OUT,">>test.out") || die;
3626 foreach (0..$records) {
3628 $q->param(-name=>'counter',-value=>$_);
3633 # reopen for reading
3634 open (IN,"test.out") || die;
3636 my $q = new CGI(IN);
3637 print $q->param('counter'),"\n";
3640 The file format used for save/restore is identical to that used by the
3641 Whitehead Genome Center's data exchange format "Boulderio", and can be
3642 manipulated and even databased using Boulderio utilities. See
3644 http://www.genome.wi.mit.edu/genome_software/other/boulder.html
3646 for further details.
3648 If you wish to use this method from the function-oriented (non-OO)
3649 interface, the exported name for this method is B<save_parameters()>.
3651 =head2 USING THE FUNCTION-ORIENTED INTERFACE
3653 To use the function-oriented interface, you must specify which CGI.pm
3654 routines or sets of routines to import into your script's namespace.
3655 There is a small overhead associated with this importation, but it
3658 use CGI <list of methods>;
3660 The listed methods will be imported into the current package; you can
3661 call them directly without creating a CGI object first. This example
3662 shows how to import the B<param()> and B<header()>
3663 methods, and then use them directly:
3665 use CGI 'param','header';
3666 print header('text/plain');
3667 $zipcode = param('zipcode');
3669 More frequently, you'll import common sets of functions by referring
3670 to the gropus by name. All function sets are preceded with a ":"
3671 character as in ":html3" (for tags defined in the HTML 3 standard).
3673 Here is a list of the function sets you can import:
3679 Import all CGI-handling methods, such as B<param()>, B<path_info()>
3684 Import all fill-out form generating methods, such as B<textfield()>.
3688 Import all methods that generate HTML 2.0 standard elements.
3692 Import all methods that generate HTML 3.0 proposed elements (such as
3693 <table>, <super> and <sub>).
3697 Import all methods that generate Netscape-specific HTML extensions.
3701 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
3706 Import "standard" features, 'html2', 'html3', 'form' and 'cgi'.
3710 Import all the available methods. For the full list, see the CGI.pm
3711 code, where the variable %TAGS is defined.
3715 If you import a function name that is not part of CGI.pm, the module
3716 will treat it as a new HTML tag and generate the appropriate
3717 subroutine. You can then use it like any other HTML tag. This is to
3718 provide for the rapidly-evolving HTML "standard." For example, say
3719 Microsoft comes out with a new tag called <GRADIENT> (which causes the
3720 user's desktop to be flooded with a rotating gradient fill until his
3721 machine reboots). You don't need to wait for a new version of CGI.pm
3722 to start using it immeidately:
3724 use CGI qw/:standard :html3 gradient/;
3725 print gradient({-start=>'red',-end=>'blue'});
3727 Note that in the interests of execution speed CGI.pm does B<not> use
3728 the standard L<Exporter> syntax for specifying load symbols. This may
3729 change in the future.
3731 If you import any of the state-maintaining CGI or form-generating
3732 methods, a default CGI object will be created and initialized
3733 automatically the first time you use any of the methods that require
3734 one to be present. This includes B<param()>, B<textfield()>,
3735 B<submit()> and the like. (If you need direct access to the CGI
3736 object, you can find it in the global variable B<$CGI::Q>). By
3737 importing CGI.pm methods, you can create visually elegant scripts:
3739 use CGI qw/:standard/;
3742 start_html('Simple Script'),
3743 h1('Simple Script'),
3745 "What's your name? ",textfield('name'),p,
3746 "What's the combination?",
3747 checkbox_group(-name=>'words',
3748 -values=>['eenie','meenie','minie','moe'],
3749 -defaults=>['eenie','moe']),p,
3750 "What's your favorite color?",
3751 popup_menu(-name=>'color',
3752 -values=>['red','green','blue','chartreuse']),p,
3759 "Your name is ",em(param('name')),p,
3760 "The keywords are: ",em(join(", ",param('words'))),p,
3761 "Your favorite color is ",em(param('color')),".\n";
3767 In addition to the function sets, there are a number of pragmas that
3768 you can import. Pragmas, which are always preceded by a hyphen,
3769 change the way that CGI.pm functions in various ways. Pragmas,
3770 function sets, and individual functions can all be imported in the
3771 same use() line. For example, the following use statement imports the
3772 standard set of functions and disables debugging mode (pragma
3775 use CGI qw/:standard -no_debug/;
3777 The current list of pragmas is as follows:
3783 When you I<use CGI -any>, then any method that the query object
3784 doesn't recognize will be interpreted as a new HTML tag. This allows
3785 you to support the next I<ad hoc> Netscape or Microsoft HTML
3786 extension. This lets you go wild with new and unsupported tags:
3790 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
3792 Since using <cite>any</cite> causes any mistyped method name
3793 to be interpreted as an HTML tag, use it with care or not at
3798 This causes the indicated autoloaded methods to be compiled up front,
3799 rather than deferred to later. This is useful for scripts that run
3800 for an extended period of time under FastCGI or mod_perl, and for
3801 those destined to be crunched by Malcom Beattie's Perl compiler. Use
3802 it in conjunction with the methods or method familes you plan to use.
3804 use CGI qw(-compile :standard :html3);
3808 use CGI qw(-compile :all);
3810 Note that using the -compile pragma in this way will always have
3811 the effect of importing the compiled functions into the current
3812 namespace. If you want to compile without importing use the
3813 compile() method instead (see below).
3817 This makes CGI.pm produce a header appropriate for an NPH (no
3818 parsed header) script. You may need to do other things as well
3819 to tell the server that the script is NPH. See the discussion
3820 of NPH scripts below.
3824 This overrides the autoloader so that any function in your program
3825 that is not recognized is referred to CGI.pm for possible evaluation.
3826 This allows you to use all the CGI.pm functions without adding them to
3827 your symbol table, which is of concern for mod_perl users who are
3828 worried about memory consumption. I<Warning:> when
3829 I<-autoload> is in effect, you cannot use "poetry mode"
3830 (functions without the parenthesis). Use I<hr()> rather
3831 than I<hr>, or add something like I<use subs qw/hr p header/>
3832 to the top of your script.
3836 This turns off the command-line processing features. If you want to
3837 run a CGI.pm script from the command line to produce HTML, and you
3838 don't want it pausing to request CGI parameters from standard input or
3839 the command line, then use this pragma:
3841 use CGI qw(-no_debug :standard);
3843 If you'd like to process the command-line parameters but not standard
3844 input, this should work:
3846 use CGI qw(-no_debug :standard);
3847 restore_parameters(join('&',@ARGV));
3849 See the section on debugging for more details.
3851 =item -private_tempfiles
3853 CGI.pm can process uploaded file. Ordinarily it spools the
3854 uploaded file to a temporary directory, then deletes the file
3855 when done. However, this opens the risk of eavesdropping as
3856 described in the file upload section.
3857 Another CGI script author could peek at this data during the
3858 upload, even if it is confidential information. On Unix systems,
3859 the -private_tempfiles pragma will cause the temporary file to be unlinked as soon
3860 as it is opened and before any data is written into it,
3861 eliminating the risk of eavesdropping.
3865 =head1 GENERATING DYNAMIC DOCUMENTS
3867 Most of CGI.pm's functions deal with creating documents on the fly.
3868 Generally you will produce the HTTP header first, followed by the
3869 document itself. CGI.pm provides functions for generating HTTP
3870 headers of various types as well as for generating HTML. For creating
3871 GIF images, see the GD.pm module.
3873 Each of these functions produces a fragment of HTML or HTTP which you
3874 can print out directly so that it displays in the browser window,
3875 append to a string, or save to a file for later use.
3877 =head2 CREATING A STANDARD HTTP HEADER:
3879 Normally the first thing you will do in any CGI script is print out an
3880 HTTP header. This tells the browser what type of document to expect,
3881 and gives other optional information, such as the language, expiration
3882 date, and whether to cache the document. The header can also be
3883 manipulated for special purposes, such as server push and pay per view
3886 print $query->header;
3890 print $query->header('image/gif');
3894 print $query->header('text/html','204 No response');
3898 print $query->header(-type=>'image/gif',
3900 -status=>'402 Payment required',
3905 header() returns the Content-type: header. You can provide your own
3906 MIME type if you choose, otherwise it defaults to text/html. An
3907 optional second parameter specifies the status code and a human-readable
3908 message. For example, you can specify 204, "No response" to create a
3909 script that tells the browser to do nothing at all.
3911 The last example shows the named argument style for passing arguments
3912 to the CGI methods using named parameters. Recognized parameters are
3913 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
3914 parameters will be stripped of their initial hyphens and turned into
3915 header fields, allowing you to specify any HTTP header you desire.
3916 Internal underscores will be turned into hyphens:
3918 print $query->header(-Content_length=>3002);
3920 Most browsers will not cache the output from CGI scripts. Every time
3921 the browser reloads the page, the script is invoked anew. You can
3922 change this behavior with the B<-expires> parameter. When you specify
3923 an absolute or relative expiration interval with this parameter, some
3924 browsers and proxy servers will cache the script's output until the
3925 indicated expiration date. The following forms are all valid for the
3928 +30s 30 seconds from now
3929 +10m ten minutes from now
3930 +1h one hour from now
3931 -1d yesterday (i.e. "ASAP!")
3934 +10y in ten years time
3935 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
3937 The B<-cookie> parameter generates a header that tells the browser to provide
3938 a "magic cookie" during all subsequent transactions with your script.
3939 Netscape cookies have a special format that includes interesting attributes
3940 such as expiration time. Use the cookie() method to create and retrieve
3943 The B<-nph> parameter, if set to a true value, will issue the correct
3944 headers to work with a NPH (no-parse-header) script. This is important
3945 to use with certain servers, such as Microsoft Internet Explorer, which
3946 expect all their scripts to be NPH.
3948 =head2 GENERATING A REDIRECTION HEADER
3950 print $query->redirect('http://somewhere.else/in/movie/land');
3952 Sometimes you don't want to produce a document yourself, but simply
3953 redirect the browser elsewhere, perhaps choosing a URL based on the
3954 time of day or the identity of the user.
3956 The redirect() function redirects the browser to a different URL. If
3957 you use redirection like this, you should B<not> print out a header as
3958 well. As of version 2.0, we produce both the unofficial Location:
3959 header and the official URI: header. This should satisfy most servers
3962 One hint I can offer is that relative links may not work correctly
3963 when you generate a redirection to another document on your site.
3964 This is due to a well-intentioned optimization that some servers use.
3965 The solution to this is to use the full URL (including the http: part)
3966 of the document you are redirecting to.
3968 You can also use named arguments:
3970 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
3973 The B<-nph> parameter, if set to a true value, will issue the correct
3974 headers to work with a NPH (no-parse-header) script. This is important
3975 to use with certain servers, such as Microsoft Internet Explorer, which
3976 expect all their scripts to be NPH.
3978 =head2 CREATING THE HTML DOCUMENT HEADER
3980 print $query->start_html(-title=>'Secrets of the Pyramids',
3981 -author=>'fred@capricorn.org',
3984 -meta=>{'keywords'=>'pharaoh secret mummy',
3985 'copyright'=>'copyright 1996 King Tut'},
3986 -style=>{'src'=>'/styles/style1.css'},
3989 After creating the HTTP header, most CGI scripts will start writing
3990 out an HTML document. The start_html() routine creates the top of the
3991 page, along with a lot of optional information that controls the
3992 page's appearance and behavior.
3994 This method returns a canned HTML header and the opening <BODY> tag.
3995 All parameters are optional. In the named parameter form, recognized
3996 parameters are -title, -author, -base, -xbase and -target (see below
3997 for the explanation). Any additional parameters you provide, such as
3998 the Netscape unofficial BGCOLOR attribute, are added to the <BODY>
3999 tag. Additional parameters must be proceeded by a hyphen.
4001 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
4002 different from the current location, as in
4004 -xbase=>"http://home.mcom.com/"
4006 All relative links will be interpreted relative to this tag.
4008 The argument B<-target> allows you to provide a default target frame
4009 for all the links and fill-out forms on the page. See the Netscape
4010 documentation on frames for details of how to manipulate this.
4012 -target=>"answer_window"
4014 All relative links will be interpreted relative to this tag.
4015 You add arbitrary meta information to the header with the B<-meta>
4016 argument. This argument expects a reference to an associative array
4017 containing name/value pairs of meta information. These will be turned
4018 into a series of header <META> tags that look something like this:
4020 <META NAME="keywords" CONTENT="pharaoh secret mummy">
4021 <META NAME="description" CONTENT="copyright 1996 King Tut">
4023 There is no support for the HTTP-EQUIV type of <META> tag. This is
4024 because you can modify the HTTP header directly with the B<header()>
4025 method. For example, if you want to send the Refresh: header, do it
4026 in the header() method:
4028 print $q->header(-Refresh=>'10; URL=http://www.capricorn.com');
4030 The B<-style> tag is used to incorporate cascading stylesheets into
4031 your code. See the section on CASCADING STYLESHEETS for more information.
4033 You can place other arbitrary HTML elements to the <HEAD> section with the
4034 B<-head> tag. For example, to place the rarely-used <LINK> element in the
4035 head section, use this:
4037 print $q->start_html(-head=>Link({-rel=>'next',
4038 -href=>'http://www.capricorn.com/s2.html'}));
4040 To incorporate multiple HTML elements into the <HEAD> section, just pass an
4043 print $q->start_html(-head=>[
4045 -href=>'http://www.capricorn.com/s2.html'}),
4046 Link({-rel=>'previous',
4047 -href=>'http://www.capricorn.com/s1.html'})
4051 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4052 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4053 to add Netscape JavaScript calls to your pages. B<-script> should
4054 point to a block of text containing JavaScript function definitions.
4055 This block will be placed within a <SCRIPT> block inside the HTML (not
4056 HTTP) header. The block is placed in the header in order to give your
4057 page a fighting chance of having all its JavaScript functions in place
4058 even if the user presses the stop button before the page has loaded
4059 completely. CGI.pm attempts to format the script in such a way that
4060 JavaScript-naive browsers will not choke on the code: unfortunately
4061 there are some browsers, such as Chimera for Unix, that get confused
4064 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4065 code to execute when the page is respectively opened and closed by the
4066 browser. Usually these parameters are calls to functions defined in the
4070 print $query->header;
4072 // Ask a silly question
4073 function riddle_me_this() {
4074 var r = prompt("What walks on four legs in the morning, " +
4075 "two legs in the afternoon, " +
4076 "and three legs in the evening?");
4079 // Get a silly answer
4080 function response(answer) {
4081 if (answer == "man")
4082 alert("Right you are!");
4084 alert("Wrong! Guess again.");
4087 print $query->start_html(-title=>'The Riddle of the Sphinx',
4090 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4091 browsers that do not have JavaScript (or browsers where JavaScript is turned
4094 Netscape 3.0 recognizes several attributes of the <SCRIPT> tag,
4095 including LANGUAGE and SRC. The latter is particularly interesting,
4096 as it allows you to keep the JavaScript code in a file or CGI script
4097 rather than cluttering up each page with the source. To use these
4098 attributes pass a HASH reference in the B<-script> parameter containing
4099 one or more of -language, -src, or -code:
4101 print $q->start_html(-title=>'The Riddle of the Sphinx',
4102 -script=>{-language=>'JAVASCRIPT',
4103 -src=>'/javascript/sphinx.js'}
4106 print $q->(-title=>'The Riddle of the Sphinx',
4107 -script=>{-language=>'PERLSCRIPT'},
4108 -code=>'print "hello world!\n;"'
4112 A final feature allows you to incorporate multiple <SCRIPT> sections into the
4113 header. Just pass the list of script sections as an array reference.
4114 this allows you to specify different source files for different dialects
4115 of JavaScript. Example:
4117 print $q->start_html(-title=>'The Riddle of the Sphinx',
4119 { -language => 'JavaScript1.0',
4120 -src => '/javascript/utilities10.js'
4122 { -language => 'JavaScript1.1',
4123 -src => '/javascript/utilities11.js'
4125 { -language => 'JavaScript1.2',
4126 -src => '/javascript/utilities12.js'
4128 { -language => 'JavaScript28.2',
4129 -src => '/javascript/utilities219.js'
4135 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4139 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4141 for more information about JavaScript.
4143 The old-style positional parameters are as follows:
4147 =item B<Parameters:>
4155 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
4159 A 'true' flag if you want to include a <BASE> tag in the header. This
4160 helps resolve relative addresses to absolute ones when the document is moved,
4161 but makes the document hierarchy non-portable. Use with care!
4165 Any other parameters you want to include in the <BODY> tag. This is a good
4166 place to put Netscape extensions, such as colors and wallpaper patterns.
4170 =head2 ENDING THE HTML DOCUMENT:
4172 print $query->end_html
4174 This ends an HTML document by printing the </BODY></HTML> tags.
4176 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4178 $myself = $query->self_url;
4179 print "<A HREF=$myself>I'm talking to myself.</A>";
4181 self_url() will return a URL, that, when selected, will reinvoke
4182 this script with all its state information intact. This is most
4183 useful when you want to jump around within the document using
4184 internal anchors but you don't want to disrupt the current contents
4185 of the form(s). Something like this will do the trick.
4187 $myself = $query->self_url;
4188 print "<A HREF=$myself#table1>See table 1</A>";
4189 print "<A HREF=$myself#table2>See table 2</A>";
4190 print "<A HREF=$myself#yourself>See for yourself</A>";
4192 If you want more control over what's returned, using the B<url()>
4195 You can also retrieve the unprocessed query string with query_string():
4197 $the_string = $query->query_string;
4199 =head2 OBTAINING THE SCRIPT'S URL
4201 $full_url = $query->url();
4202 $full_url = $query->url(-full=>1); #alternative syntax
4203 $relative_url = $query->url(-relative=>1);
4204 $absolute_url = $query->url(-absolute=>1);
4205 $url_with_path = $query->url(-path_info=>1);
4206 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4208 B<url()> returns the script's URL in a variety of formats. Called
4209 without any arguments, it returns the full form of the URL, including
4210 host name and port number
4212 http://your.host.com/path/to/script.cgi
4214 You can modify this format with the following named arguments:
4220 If true, produce an absolute URL, e.g.
4226 Produce a relative URL. This is useful if you want to reinvoke your
4227 script with different parameters. For example:
4233 Produce the full URL, exactly as if called without any arguments.
4234 This overrides the -relative and -absolute arguments.
4236 =item B<-path> (B<-path_info>)
4238 Append the additional path information to the URL. This can be
4239 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
4240 is provided as a synonym.
4242 =item B<-query> (B<-query_string>)
4244 Append the query string to the URL. This can be combined with
4245 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
4250 =head1 CREATING STANDARD HTML ELEMENTS:
4252 CGI.pm defines general HTML shortcut methods for most, if not all of
4253 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
4254 HTML element and return a fragment of HTML text that you can then
4255 print or manipulate as you like. Each shortcut returns a fragment of
4256 HTML code that you can append to a string, save to a file, or, most
4257 commonly, print out so that it displays in the browser window.
4259 This example shows how to use the HTML methods:
4262 print $q->blockquote(
4263 "Many years ago on the island of",
4264 $q->a({href=>"http://crete.org/"},"Crete"),
4265 "there lived a minotaur named",
4266 $q->strong("Fred."),
4270 This results in the following HTML code (extra newlines have been
4271 added for readability):
4274 Many years ago on the island of
4275 <a HREF="http://crete.org/">Crete</a> there lived
4276 a minotaur named <strong>Fred.</strong>
4280 If you find the syntax for calling the HTML shortcuts awkward, you can
4281 import them into your namespace and dispense with the object syntax
4282 completely (see the next section for more details):
4284 use CGI ':standard';
4286 "Many years ago on the island of",
4287 a({href=>"http://crete.org/"},"Crete"),
4288 "there lived a minotaur named",
4293 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4295 The HTML methods will accept zero, one or multiple arguments. If you
4296 provide no arguments, you get a single tag:
4300 If you provide one or more string arguments, they are concatenated
4301 together with spaces and placed between opening and closing tags:
4303 print h1("Chapter","1"); # <H1>Chapter 1</H1>"
4305 If the first argument is an associative array reference, then the keys
4306 and values of the associative array become the HTML tag's attributes:
4308 print a({-href=>'fred.html',-target=>'_new'},
4309 "Open a new frame");
4311 <A HREF="fred.html",TARGET="_new">Open a new frame</A>
4313 You may dispense with the dashes in front of the attribute names if
4316 print img {src=>'fred.gif',align=>'LEFT'};
4318 <IMG ALIGN="LEFT" SRC="fred.gif">
4320 Sometimes an HTML tag attribute has no argument. For example, ordered
4321 lists can be marked as COMPACT. The syntax for this is an argument that
4322 that points to an undef string:
4324 print ol({compact=>undef},li('one'),li('two'),li('three'));
4326 Prior to CGI.pm version 2.41, providing an empty ('') string as an
4327 attribute argument was the same as providing undef. However, this has
4328 changed in order to accomodate those who want to create tags of the form
4329 <IMG ALT="">. The difference is shown in these two pieces of code:
4332 img({alt=>undef}) <IMG ALT>
4333 img({alt=>''}) <IMT ALT="">
4335 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
4337 One of the cool features of the HTML shortcuts is that they are
4338 distributive. If you give them an argument consisting of a
4339 B<reference> to a list, the tag will be distributed across each
4340 element of the list. For example, here's one way to make an ordered
4344 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy']);
4347 This example will result in HTML output that looks like this:
4350 <LI TYPE="disc">Sneezy</LI>
4351 <LI TYPE="disc">Doc</LI>
4352 <LI TYPE="disc">Sleepy</LI>
4353 <LI TYPE="disc">Happy</LI>
4356 This is extremely useful for creating tables. For example:
4358 print table({-border=>undef},
4359 caption('When Should You Eat Your Vegetables?'),
4360 Tr({-align=>CENTER,-valign=>TOP},
4362 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
4363 td(['Tomatoes' , 'no', 'yes', 'yes']),
4364 td(['Broccoli' , 'no', 'no', 'yes']),
4365 td(['Onions' , 'yes','yes', 'yes'])
4370 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
4372 Consider this bit of code:
4374 print blockquote(em('Hi'),'mom!'));
4376 It will ordinarily return the string that you probably expect, namely:
4378 <BLOCKQUOTE><EM>Hi</EM> mom!</BLOCKQUOTE>
4380 Note the space between the element "Hi" and the element "mom!".
4381 CGI.pm puts the extra space there using array interpolation, which is
4382 controlled by the magic $" variable. Sometimes this extra space is
4383 not what you want, for example, when you are trying to align a series
4384 of images. In this case, you can simply change the value of $" to an
4389 print blockquote(em('Hi'),'mom!'));
4392 I suggest you put the code in a block as shown here. Otherwise the
4393 change to $" will affect all subsequent code until you explicitly
4396 =head2 NON-STANDARD HTML SHORTCUTS
4398 A few HTML tags don't follow the standard pattern for various
4401 B<comment()> generates an HTML comment (<!-- comment -->). Call it
4404 print comment('here is my comment');
4406 Because of conflicts with built-in Perl functions, the following functions
4407 begin with initial caps:
4414 In addition, start_html(), end_html(), start_form(), end_form(),
4415 start_multipart_form() and all the fill-out form tags are special.
4416 See their respective sections.
4418 =head1 CREATING FILL-OUT FORMS:
4420 I<General note> The various form-creating methods all return strings
4421 to the caller, containing the tag or tags that will create the requested
4422 form element. You are responsible for actually printing out these strings.
4423 It's set up this way so that you can place formatting tags
4424 around the form elements.
4426 I<Another note> The default values that you specify for the forms are only
4427 used the B<first> time the script is invoked (when there is no query
4428 string). On subsequent invocations of the script (when there is a query
4429 string), the former values are used even if they are blank.
4431 If you want to change the value of a field from its previous value, you have two
4434 (1) call the param() method to set it.
4436 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
4437 This forces the default value to be used, regardless of the previous value:
4439 print $query->textfield(-name=>'field_name',
4440 -default=>'starting value',
4445 I<Yet another note> By default, the text and labels of form elements are
4446 escaped according to HTML rules. This means that you can safely use
4447 "<CLICK ME>" as the label for a button. However, it also interferes with
4448 your ability to incorporate special HTML character sequences, such as Á,
4449 into your fields. If you wish to turn off automatic escaping, call the
4450 autoEscape() method with a false value immediately after creating the CGI object:
4453 $query->autoEscape(undef);
4456 =head2 CREATING AN ISINDEX TAG
4458 print $query->isindex(-action=>$action);
4462 print $query->isindex($action);
4464 Prints out an <ISINDEX> tag. Not very exciting. The parameter
4465 -action specifies the URL of the script to process the query. The
4466 default is to process the query with the current script.
4468 =head2 STARTING AND ENDING A FORM
4470 print $query->startform(-method=>$method,
4472 -encoding=>$encoding);
4473 <... various form stuff ...>
4474 print $query->endform;
4478 print $query->startform($method,$action,$encoding);
4479 <... various form stuff ...>
4480 print $query->endform;
4482 startform() will return a <FORM> tag with the optional method,
4483 action and form encoding that you specify. The defaults are:
4487 encoding: application/x-www-form-urlencoded
4489 endform() returns the closing </FORM> tag.
4491 Startform()'s encoding method tells the browser how to package the various
4492 fields of the form before sending the form to the server. Two
4493 values are possible:
4497 =item B<application/x-www-form-urlencoded>
4499 This is the older type of encoding used by all browsers prior to
4500 Netscape 2.0. It is compatible with many CGI scripts and is
4501 suitable for short fields containing text data. For your
4502 convenience, CGI.pm stores the name of this encoding
4503 type in B<$CGI::URL_ENCODED>.
4505 =item B<multipart/form-data>
4507 This is the newer type of encoding introduced by Netscape 2.0.
4508 It is suitable for forms that contain very large fields or that
4509 are intended for transferring binary data. Most importantly,
4510 it enables the "file upload" feature of Netscape 2.0 forms. For
4511 your convenience, CGI.pm stores the name of this encoding type
4512 in B<&CGI::MULTIPART>
4514 Forms that use this type of encoding are not easily interpreted
4515 by CGI scripts unless they use CGI.pm or another library designed
4520 For compatibility, the startform() method uses the older form of
4521 encoding by default. If you want to use the newer form of encoding
4522 by default, you can call B<start_multipart_form()> instead of
4525 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
4526 for use with JavaScript. The -name parameter gives the
4527 form a name so that it can be identified and manipulated by
4528 JavaScript functions. -onSubmit should point to a JavaScript
4529 function that will be executed just before the form is submitted to your
4530 server. You can use this opportunity to check the contents of the form
4531 for consistency and completeness. If you find something wrong, you
4532 can put up an alert box or maybe fix things up yourself. You can
4533 abort the submission by returning false from this function.
4535 Usually the bulk of JavaScript functions are defined in a <SCRIPT>
4536 block in the HTML header and -onSubmit points to one of these function
4537 call. See start_html() for details.
4539 =head2 CREATING A TEXT FIELD
4541 print $query->textfield(-name=>'field_name',
4542 -default=>'starting value',
4547 print $query->textfield('field_name','starting value',50,80);
4549 textfield() will return a text input field.
4557 The first parameter is the required name for the field (-name).
4561 The optional second parameter is the default starting value for the field
4562 contents (-default).
4566 The optional third parameter is the size of the field in
4571 The optional fourth parameter is the maximum number of characters the
4572 field will accept (-maxlength).
4576 As with all these methods, the field will be initialized with its
4577 previous contents from earlier invocations of the script.
4578 When the form is processed, the value of the text field can be
4581 $value = $query->param('foo');
4583 If you want to reset it from its initial value after the script has been
4584 called once, you can do so like this:
4586 $query->param('foo',"I'm taking over this value!");
4588 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
4589 value, you can force its current value by using the -override (alias -force)
4592 print $query->textfield(-name=>'field_name',
4593 -default=>'starting value',
4598 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
4599 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
4600 parameters to register JavaScript event handlers. The onChange
4601 handler will be called whenever the user changes the contents of the
4602 text field. You can do text validation if you like. onFocus and
4603 onBlur are called respectively when the insertion point moves into and
4604 out of the text field. onSelect is called when the user changes the
4605 portion of the text that is selected.
4607 =head2 CREATING A BIG TEXT FIELD
4609 print $query->textarea(-name=>'foo',
4610 -default=>'starting value',
4616 print $query->textarea('foo','starting value',10,50);
4618 textarea() is just like textfield, but it allows you to specify
4619 rows and columns for a multiline text entry box. You can provide
4620 a starting value for the field, which can be long and contain
4623 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
4624 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
4625 recognized. See textfield().
4627 =head2 CREATING A PASSWORD FIELD
4629 print $query->password_field(-name=>'secret',
4630 -value=>'starting value',
4635 print $query->password_field('secret','starting value',50,80);
4637 password_field() is identical to textfield(), except that its contents
4638 will be starred out on the web page.
4640 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
4641 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
4642 recognized. See textfield().
4644 =head2 CREATING A FILE UPLOAD FIELD
4646 print $query->filefield(-name=>'uploaded_file',
4647 -default=>'starting value',
4652 print $query->filefield('uploaded_file','starting value',50,80);
4654 filefield() will return a file upload field for Netscape 2.0 browsers.
4655 In order to take full advantage of this I<you must use the new
4656 multipart encoding scheme> for the form. You can do this either
4657 by calling B<startform()> with an encoding type of B<$CGI::MULTIPART>,
4658 or by calling the new method B<start_multipart_form()> instead of
4659 vanilla B<startform()>.
4667 The first parameter is the required name for the field (-name).
4671 The optional second parameter is the starting value for the field contents
4672 to be used as the default file name (-default).
4674 The beta2 version of Netscape 2.0 currently doesn't pay any attention
4675 to this field, and so the starting value will always be blank. Worse,
4676 the field loses its "sticky" behavior and forgets its previous
4677 contents. The starting value field is called for in the HTML
4678 specification, however, and possibly later versions of Netscape will
4683 The optional third parameter is the size of the field in
4688 The optional fourth parameter is the maximum number of characters the
4689 field will accept (-maxlength).
4693 When the form is processed, you can retrieve the entered filename
4696 $filename = $query->param('uploaded_file');
4698 In Netscape Navigator 2.0, the filename that gets returned is the full
4699 local filename on the B<remote user's> machine. If the remote user is
4700 on a Unix machine, the filename will follow Unix conventions:
4704 On an MS-DOS/Windows and OS/2 machines, the filename will follow DOS conventions:
4706 C:\PATH\TO\THE\FILE.MSW
4708 On a Macintosh machine, the filename will follow Mac conventions:
4710 HD 40:Desktop Folder:Sort Through:Reminders
4712 The filename returned is also a file handle. You can read the contents
4713 of the file using standard Perl file reading calls:
4715 # Read a text file and print it out
4716 while (<$filename>) {
4720 # Copy a binary file to somewhere safe
4721 open (OUTFILE,">>/usr/local/web/users/feedback");
4722 while ($bytesread=read($filename,$buffer,1024)) {
4723 print OUTFILE $buffer;
4726 When a file is uploaded the browser usually sends along some
4727 information along with it in the format of headers. The information
4728 usually includes the MIME content type. Future browsers may send
4729 other information as well (such as modification date and size). To
4730 retrieve this information, call uploadInfo(). It returns a reference to
4731 an associative array containing all the document headers.
4733 $filename = $query->param('uploaded_file');
4734 $type = $query->uploadInfo($filename)->{'Content-Type'};
4735 unless ($type eq 'text/html') {
4736 die "HTML FILES ONLY!";
4739 If you are using a machine that recognizes "text" and "binary" data
4740 modes, be sure to understand when and how to use them (see the Camel book).
4741 Otherwise you may find that binary files are corrupted during file uploads.
4743 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
4744 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
4745 recognized. See textfield() for details.
4747 =head2 CREATING A POPUP MENU
4749 print $query->popup_menu('menu_name',
4750 ['eenie','meenie','minie'],
4755 %labels = ('eenie'=>'your first choice',
4756 'meenie'=>'your second choice',
4757 'minie'=>'your third choice');
4758 print $query->popup_menu('menu_name',
4759 ['eenie','meenie','minie'],
4762 -or (named parameter style)-
4764 print $query->popup_menu(-name=>'menu_name',
4765 -values=>['eenie','meenie','minie'],
4769 popup_menu() creates a menu.
4775 The required first argument is the menu's name (-name).
4779 The required second argument (-values) is an array B<reference>
4780 containing the list of menu items in the menu. You can pass the
4781 method an anonymous array, as shown in the example, or a reference to
4782 a named array, such as "\@foo".
4786 The optional third parameter (-default) is the name of the default
4787 menu choice. If not specified, the first item will be the default.
4788 The values of the previous choice will be maintained across queries.
4792 The optional fourth parameter (-labels) is provided for people who
4793 want to use different values for the user-visible label inside the
4794 popup menu nd the value returned to your script. It's a pointer to an
4795 associative array relating menu values to user-visible labels. If you
4796 leave this parameter blank, the menu values will be displayed by
4797 default. (You can also leave a label undefined if you want to).
4801 When the form is processed, the selected value of the popup menu can
4804 $popup_menu_value = $query->param('menu_name');
4806 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
4807 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
4808 B<-onBlur>. See the textfield() section for details on when these
4809 handlers are called.
4811 =head2 CREATING A SCROLLING LIST
4813 print $query->scrolling_list('list_name',
4814 ['eenie','meenie','minie','moe'],
4815 ['eenie','moe'],5,'true');
4818 print $query->scrolling_list('list_name',
4819 ['eenie','meenie','minie','moe'],
4820 ['eenie','moe'],5,'true',
4825 print $query->scrolling_list(-name=>'list_name',
4826 -values=>['eenie','meenie','minie','moe'],
4827 -default=>['eenie','moe'],
4832 scrolling_list() creates a scrolling list.
4836 =item B<Parameters:>
4840 The first and second arguments are the list name (-name) and values
4841 (-values). As in the popup menu, the second argument should be an
4846 The optional third argument (-default) can be either a reference to a
4847 list containing the values to be selected by default, or can be a
4848 single value to select. If this argument is missing or undefined,
4849 then nothing is selected when the list first appears. In the named
4850 parameter version, you can use the synonym "-defaults" for this
4855 The optional fourth argument is the size of the list (-size).
4859 The optional fifth argument can be set to true to allow multiple
4860 simultaneous selections (-multiple). Otherwise only one selection
4861 will be allowed at a time.
4865 The optional sixth argument is a pointer to an associative array
4866 containing long user-visible labels for the list items (-labels).
4867 If not provided, the values will be displayed.
4869 When this form is processed, all selected list items will be returned as
4870 a list under the parameter name 'list_name'. The values of the
4871 selected items can be retrieved with:
4873 @selected = $query->param('list_name');
4877 JAVASCRIPTING: scrolling_list() recognizes the following event
4878 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
4879 and B<-onBlur>. See textfield() for the description of when these
4880 handlers are called.
4882 =head2 CREATING A GROUP OF RELATED CHECKBOXES
4884 print $query->checkbox_group(-name=>'group_name',
4885 -values=>['eenie','meenie','minie','moe'],
4886 -default=>['eenie','moe'],
4890 print $query->checkbox_group('group_name',
4891 ['eenie','meenie','minie','moe'],
4892 ['eenie','moe'],'true',\%labels);
4894 HTML3-COMPATIBLE BROWSERS ONLY:
4896 print $query->checkbox_group(-name=>'group_name',
4897 -values=>['eenie','meenie','minie','moe'],
4898 -rows=2,-columns=>2);
4901 checkbox_group() creates a list of checkboxes that are related
4906 =item B<Parameters:>
4910 The first and second arguments are the checkbox name and values,
4911 respectively (-name and -values). As in the popup menu, the second
4912 argument should be an array reference. These values are used for the
4913 user-readable labels printed next to the checkboxes as well as for the
4914 values passed to your script in the query string.
4918 The optional third argument (-default) can be either a reference to a
4919 list containing the values to be checked by default, or can be a
4920 single value to checked. If this argument is missing or undefined,
4921 then nothing is selected when the list first appears.
4925 The optional fourth argument (-linebreak) can be set to true to place
4926 line breaks between the checkboxes so that they appear as a vertical
4927 list. Otherwise, they will be strung together on a horizontal line.
4931 The optional fifth argument is a pointer to an associative array
4932 relating the checkbox values to the user-visible labels that will
4933 be printed next to them (-labels). If not provided, the values will
4934 be used as the default.
4938 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
4939 the optional parameters B<-rows>, and B<-columns>. These parameters
4940 cause checkbox_group() to return an HTML3 compatible table containing
4941 the checkbox group formatted with the specified number of rows and
4942 columns. You can provide just the -columns parameter if you wish;
4943 checkbox_group will calculate the correct number of rows for you.
4945 To include row and column headings in the returned table, you
4946 can use the B<-rowheaders> and B<-colheaders> parameters. Both
4947 of these accept a pointer to an array of headings to use.
4948 The headings are just decorative. They don't reorganize the
4949 interpretation of the checkboxes -- they're still a single named
4954 When the form is processed, all checked boxes will be returned as
4955 a list under the parameter name 'group_name'. The values of the
4956 "on" checkboxes can be retrieved with:
4958 @turned_on = $query->param('group_name');
4960 The value returned by checkbox_group() is actually an array of button
4961 elements. You can capture them and use them within tables, lists,
4962 or in other creative ways:
4964 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
4965 &use_in_creative_way(@h);
4967 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
4968 parameter. This specifies a JavaScript code fragment or
4969 function call to be executed every time the user clicks on
4970 any of the buttons in the group. You can retrieve the identity
4971 of the particular button clicked on using the "this" variable.
4973 =head2 CREATING A STANDALONE CHECKBOX
4975 print $query->checkbox(-name=>'checkbox_name',
4976 -checked=>'checked',
4978 -label=>'CLICK ME');
4982 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
4984 checkbox() is used to create an isolated checkbox that isn't logically
4985 related to any others.
4989 =item B<Parameters:>
4993 The first parameter is the required name for the checkbox (-name). It
4994 will also be used for the user-readable label printed next to the
4999 The optional second parameter (-checked) specifies that the checkbox
5000 is turned on by default. Synonyms are -selected and -on.
5004 The optional third parameter (-value) specifies the value of the
5005 checkbox when it is checked. If not provided, the word "on" is
5010 The optional fourth parameter (-label) is the user-readable label to
5011 be attached to the checkbox. If not provided, the checkbox name is
5016 The value of the checkbox can be retrieved using:
5018 $turned_on = $query->param('checkbox_name');
5020 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
5021 parameter. See checkbox_group() for further details.
5023 =head2 CREATING A RADIO BUTTON GROUP
5025 print $query->radio_group(-name=>'group_name',
5026 -values=>['eenie','meenie','minie'],
5033 print $query->radio_group('group_name',['eenie','meenie','minie'],
5034 'meenie','true',\%labels);
5037 HTML3-COMPATIBLE BROWSERS ONLY:
5039 print $query->radio_group(-name=>'group_name',
5040 -values=>['eenie','meenie','minie','moe'],
5041 -rows=2,-columns=>2);
5043 radio_group() creates a set of logically-related radio buttons
5044 (turning one member of the group on turns the others off)
5048 =item B<Parameters:>
5052 The first argument is the name of the group and is required (-name).
5056 The second argument (-values) is the list of values for the radio
5057 buttons. The values and the labels that appear on the page are
5058 identical. Pass an array I<reference> in the second argument, either
5059 using an anonymous array, as shown, or by referencing a named array as
5064 The optional third parameter (-default) is the name of the default
5065 button to turn on. If not specified, the first item will be the
5066 default. You can provide a nonexistent button name, such as "-" to
5067 start up with no buttons selected.
5071 The optional fourth parameter (-linebreak) can be set to 'true' to put
5072 line breaks between the buttons, creating a vertical list.
5076 The optional fifth parameter (-labels) is a pointer to an associative
5077 array relating the radio button values to user-visible labels to be
5078 used in the display. If not provided, the values themselves are
5083 B<HTML3-compatible browsers> (such as Netscape) can take advantage
5085 parameters B<-rows>, and B<-columns>. These parameters cause
5086 radio_group() to return an HTML3 compatible table containing
5087 the radio group formatted with the specified number of rows
5088 and columns. You can provide just the -columns parameter if you
5089 wish; radio_group will calculate the correct number of rows
5092 To include row and column headings in the returned table, you
5093 can use the B<-rowheader> and B<-colheader> parameters. Both
5094 of these accept a pointer to an array of headings to use.
5095 The headings are just decorative. They don't reorganize the
5096 interpetation of the radio buttons -- they're still a single named
5101 When the form is processed, the selected radio button can
5104 $which_radio_button = $query->param('group_name');
5106 The value returned by radio_group() is actually an array of button
5107 elements. You can capture them and use them within tables, lists,
5108 or in other creative ways:
5110 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
5111 &use_in_creative_way(@h);
5113 =head2 CREATING A SUBMIT BUTTON
5115 print $query->submit(-name=>'button_name',
5120 print $query->submit('button_name','value');
5122 submit() will create the query submission button. Every form
5123 should have one of these.
5127 =item B<Parameters:>
5131 The first argument (-name) is optional. You can give the button a
5132 name if you have several submission buttons in your form and you want
5133 to distinguish between them. The name will also be used as the
5134 user-visible label. Be aware that a few older browsers don't deal with this correctly and
5135 B<never> send back a value from a button.
5139 The second argument (-value) is also optional. This gives the button
5140 a value that will be passed to your script in the query string.
5144 You can figure out which button was pressed by using different
5145 values for each one:
5147 $which_one = $query->param('button_name');
5149 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
5150 parameter. See checkbox_group() for further details.
5152 =head2 CREATING A RESET BUTTON
5156 reset() creates the "reset" button. Note that it restores the
5157 form to its value from the last time the script was called,
5158 NOT necessarily to the defaults.
5160 =head2 CREATING A DEFAULT BUTTON
5162 print $query->defaults('button_label')
5164 defaults() creates a button that, when invoked, will cause the
5165 form to be completely reset to its defaults, wiping out all the
5166 changes the user ever made.
5168 =head2 CREATING A HIDDEN FIELD
5170 print $query->hidden(-name=>'hidden_name',
5171 -default=>['value1','value2'...]);
5175 print $query->hidden('hidden_name','value1','value2'...);
5177 hidden() produces a text field that can't be seen by the user. It
5178 is useful for passing state variable information from one invocation
5179 of the script to the next.
5183 =item B<Parameters:>
5187 The first argument is required and specifies the name of this
5192 The second argument is also required and specifies its value
5193 (-default). In the named parameter style of calling, you can provide
5194 a single value here or a reference to a whole list
5198 Fetch the value of a hidden field this way:
5200 $hidden_value = $query->param('hidden_name');
5202 Note, that just like all the other form elements, the value of a
5203 hidden field is "sticky". If you want to replace a hidden field with
5204 some other values after the script has been called once you'll have to
5207 $query->param('hidden_name','new','values','here');
5209 =head2 CREATING A CLICKABLE IMAGE BUTTON
5211 print $query->image_button(-name=>'button_name',
5212 -src=>'/source/URL',
5217 print $query->image_button('button_name','/source/URL','MIDDLE');
5219 image_button() produces a clickable image. When it's clicked on the
5220 position of the click is returned to your script as "button_name.x"
5221 and "button_name.y", where "button_name" is the name you've assigned
5224 JAVASCRIPTING: image_button() recognizes the B<-onClick>
5225 parameter. See checkbox_group() for further details.
5229 =item B<Parameters:>
5233 The first argument (-name) is required and specifies the name of this
5238 The second argument (-src) is also required and specifies the URL
5241 The third option (-align, optional) is an alignment type, and may be
5242 TOP, BOTTOM or MIDDLE
5246 Fetch the value of the button this way:
5247 $x = $query->param('button_name.x');
5248 $y = $query->param('button_name.y');
5250 =head2 CREATING A JAVASCRIPT ACTION BUTTON
5252 print $query->button(-name=>'button_name',
5253 -value=>'user visible label',
5254 -onClick=>"do_something()");
5258 print $query->button('button_name',"do_something()");
5260 button() produces a button that is compatible with Netscape 2.0's
5261 JavaScript. When it's pressed the fragment of JavaScript code
5262 pointed to by the B<-onClick> parameter will be executed. On
5263 non-Netscape browsers this form element will probably not even
5266 =head1 NETSCAPE COOKIES
5268 Netscape browsers versions 1.1 and higher support a so-called
5269 "cookie" designed to help maintain state within a browser session.
5270 CGI.pm has several methods that support cookies.
5272 A cookie is a name=value pair much like the named parameters in a CGI
5273 query string. CGI scripts create one or more cookies and send
5274 them to the browser in the HTTP header. The browser maintains a list
5275 of cookies that belong to a particular Web server, and returns them
5276 to the CGI script during subsequent interactions.
5278 In addition to the required name=value pair, each cookie has several
5279 optional attributes:
5283 =item 1. an expiration time
5285 This is a time/date string (in a special GMT format) that indicates
5286 when a cookie expires. The cookie will be saved and returned to your
5287 script until this expiration date is reached if the user exits
5288 Netscape and restarts it. If an expiration date isn't specified, the cookie
5289 will remain active until the user quits Netscape.
5293 This is a partial or complete domain name for which the cookie is
5294 valid. The browser will return the cookie to any host that matches
5295 the partial domain name. For example, if you specify a domain name
5296 of ".capricorn.com", then Netscape will return the cookie to
5297 Web servers running on any of the machines "www.capricorn.com",
5298 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
5299 must contain at least two periods to prevent attempts to match
5300 on top level domains like ".edu". If no domain is specified, then
5301 the browser will only return the cookie to servers on the host the
5302 cookie originated from.
5306 If you provide a cookie path attribute, the browser will check it
5307 against your script's URL before returning the cookie. For example,
5308 if you specify the path "/cgi-bin", then the cookie will be returned
5309 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
5310 and "/cgi-bin/customer_service/complain.pl", but not to the script
5311 "/cgi-private/site_admin.pl". By default, path is set to "/", which
5312 causes the cookie to be sent to any CGI script on your site.
5314 =item 4. a "secure" flag
5316 If the "secure" attribute is set, the cookie will only be sent to your
5317 script if the CGI request is occurring on a secure channel, such as SSL.
5321 The interface to Netscape cookies is the B<cookie()> method:
5323 $cookie = $query->cookie(-name=>'sessionID',
5326 -path=>'/cgi-bin/database',
5327 -domain=>'.capricorn.org',
5329 print $query->header(-cookie=>$cookie);
5331 B<cookie()> creates a new cookie. Its parameters include:
5337 The name of the cookie (required). This can be any string at all.
5338 Although Netscape limits its cookie names to non-whitespace
5339 alphanumeric characters, CGI.pm removes this restriction by escaping
5340 and unescaping cookies behind the scenes.
5344 The value of the cookie. This can be any scalar value,
5345 array reference, or even associative array reference. For example,
5346 you can store an entire associative array into a cookie this way:
5348 $cookie=$query->cookie(-name=>'family information',
5349 -value=>\%childrens_ages);
5353 The optional partial path for which this cookie will be valid, as described
5358 The optional partial domain for which this cookie will be valid, as described
5363 The optional expiration date for this cookie. The format is as described
5364 in the section on the B<header()> method:
5366 "+1h" one hour from now
5370 If set to true, this cookie will only be used within a secure
5375 The cookie created by cookie() must be incorporated into the HTTP
5376 header within the string returned by the header() method:
5378 print $query->header(-cookie=>$my_cookie);
5380 To create multiple cookies, give header() an array reference:
5382 $cookie1 = $query->cookie(-name=>'riddle_name',
5383 -value=>"The Sphynx's Question");
5384 $cookie2 = $query->cookie(-name=>'answers',
5386 print $query->header(-cookie=>[$cookie1,$cookie2]);
5388 To retrieve a cookie, request it by name by calling cookie()
5389 method without the B<-value> parameter:
5393 %answers = $query->cookie(-name=>'answers');
5394 # $query->cookie('answers') will work too!
5396 The cookie and CGI namespaces are separate. If you have a parameter
5397 named 'answers' and a cookie named 'answers', the values retrieved by
5398 param() and cookie() are independent of each other. However, it's
5399 simple to turn a CGI parameter into a cookie, and vice-versa:
5401 # turn a CGI parameter into a cookie
5402 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
5404 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
5406 See the B<cookie.cgi> example script for some ideas on how to use
5407 cookies effectively.
5409 B<NOTE:> There appear to be some (undocumented) restrictions on
5410 Netscape cookies. In Netscape 2.01, at least, I haven't been able to
5411 set more than three cookies at a time. There may also be limits on
5412 the length of cookies. If you need to store a lot of information,
5413 it's probably better to create a unique session ID, store it in a
5414 cookie, and use the session ID to locate an external file/database
5415 saved on the server's side of the connection.
5417 =head1 WORKING WITH NETSCAPE FRAMES
5419 It's possible for CGI.pm scripts to write into several browser
5420 panels and windows using Netscape's frame mechanism.
5421 There are three techniques for defining new frames programmatically:
5425 =item 1. Create a <Frameset> document
5427 After writing out the HTTP header, instead of creating a standard
5428 HTML document using the start_html() call, create a <FRAMESET>
5429 document that defines the frames on the page. Specify your script(s)
5430 (with appropriate parameters) as the SRC for each of the frames.
5432 There is no specific support for creating <FRAMESET> sections
5433 in CGI.pm, but the HTML is very simple to write. See the frame
5434 documentation in Netscape's home pages for details
5436 http://home.netscape.com/assist/net_sites/frames.html
5438 =item 2. Specify the destination for the document in the HTTP header
5440 You may provide a B<-target> parameter to the header() method:
5442 print $q->header(-target=>'ResultsWindow');
5444 This will tell Netscape to load the output of your script into the
5445 frame named "ResultsWindow". If a frame of that name doesn't
5446 already exist, Netscape will pop up a new window and load your
5447 script's document into that. There are a number of magic names
5448 that you can use for targets. See the frame documents on Netscape's
5449 home pages for details.
5451 =item 3. Specify the destination for the document in the <FORM> tag
5453 You can specify the frame to load in the FORM tag itself. With
5454 CGI.pm it looks like this:
5456 print $q->startform(-target=>'ResultsWindow');
5458 When your script is reinvoked by the form, its output will be loaded
5459 into the frame named "ResultsWindow". If one doesn't already exist
5460 a new window will be created.
5464 The script "frameset.cgi" in the examples directory shows one way to
5465 create pages in which the fill-out form and the response live in
5466 side-by-side frames.
5468 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
5470 CGI.pm has limited support for HTML3's cascading style sheets (css).
5471 To incorporate a stylesheet into your document, pass the
5472 start_html() method a B<-style> parameter. The value of this
5473 parameter may be a scalar, in which case it is incorporated directly
5474 into a <STYLE> section, or it may be a hash reference. In the latter
5475 case you should provide the hash with one or more of B<-src> or
5476 B<-code>. B<-src> points to a URL where an externally-defined
5477 stylesheet can be found. B<-code> points to a scalar value to be
5478 incorporated into a <STYLE> section. Style definitions in B<-code>
5479 override similarly-named ones in B<-src>, hence the name "cascading."
5481 You may also specify the type of the stylesheet by adding the optional
5482 B<-type> parameter to the hash pointed to by B<-style>. If not
5483 specified, the style defaults to 'text/css'.
5485 To refer to a style within the body of your document, add the
5486 B<-class> parameter to any HTML element:
5488 print h1({-class=>'Fancy'},'Welcome to the Party');
5490 Or define styles on the fly with the B<-style> parameter:
5492 print h1({-style=>'Color: red;'},'Welcome to Hell');
5494 You may also use the new B<span()> element to apply a style to a
5497 print span({-style=>'Color: red;'},
5498 h1('Welcome to Hell'),
5499 "Where did that handbasket get to?"
5502 Note that you must import the ":html3" definitions to have the
5503 B<span()> method available. Here's a quick and dirty example of using
5504 CSS's. See the CSS specification at
5505 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
5507 use CGI qw/:standard :html3/;
5509 #here's a stylesheet incorporated directly into the page
5519 font-family: sans-serif;
5525 print start_html( -title=>'CGI with Style',
5526 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
5529 print h1('CGI with Style'),
5531 "Better read the cascading style sheet spec before playing with this!"),
5532 span({-style=>'color: magenta'},
5533 "Look Mom, no hands!",
5541 If you are running the script
5542 from the command line or in the perl debugger, you can pass the script
5543 a list of keywords or parameter=value pairs on the command line or
5544 from standard input (you don't have to worry about tricking your
5545 script into reading from environment variables).
5546 You can pass keywords like this:
5548 your_script.pl keyword1 keyword2 keyword3
5552 your_script.pl keyword1+keyword2+keyword3
5556 your_script.pl name1=value1 name2=value2
5560 your_script.pl name1=value1&name2=value2
5562 or even as newline-delimited parameters on standard input.
5564 When debugging, you can use quotes and backslashes to escape
5565 characters in the familiar shell manner, letting you place
5566 spaces and other funny characters in your parameter=value
5569 your_script.pl "name1='I am a long value'" "name2=two\ words"
5571 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
5573 The dump() method produces a string consisting of all the query's
5574 name/value pairs formatted nicely as a nested list. This is useful
5575 for debugging purposes:
5580 Produces something that looks like:
5594 You can pass a value of 'true' to dump() in order to get it to
5595 print the results out as plain text, suitable for incorporating
5596 into a <PRE> section.
5598 As a shortcut, as of version 1.56 you can interpolate the entire CGI
5599 object into a string and it will be replaced with the a nice HTML dump
5603 print "<H2>Current Values</H2> $query\n";
5605 =head1 FETCHING ENVIRONMENT VARIABLES
5607 Some of the more useful environment variables can be fetched
5608 through this interface. The methods are as follows:
5614 Return a list of MIME types that the remote browser
5615 accepts. If you give this method a single argument
5616 corresponding to a MIME type, as in
5617 $query->accept('text/html'), it will return a
5618 floating point value corresponding to the browser's
5619 preference for this type from 0.0 (don't want) to 1.0.
5620 Glob types (e.g. text/*) in the browser's accept list
5621 are handled correctly.
5623 =item B<raw_cookie()>
5625 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
5626 Netscape browsers version 1.1 and higher. Cookies have a special
5627 format, and this method call just returns the raw form (?cookie
5628 dough). See cookie() for ways of setting and retrieving cooked
5631 Called with no parameters, raw_cookie() returns the packed cookie
5632 structure. You can separate it into individual cookies by splitting
5633 on the character sequence "; ". Called with the name of a cookie,
5634 retrieves the B<unescaped> form of the cookie. You can use the
5635 regular cookie() method to get the names, or use the raw_fetch()
5636 method from the CGI::Cookie module.
5638 =item B<user_agent()>
5640 Returns the HTTP_USER_AGENT variable. If you give
5641 this method a single argument, it will attempt to
5642 pattern match on it, allowing you to do something
5643 like $query->user_agent(netscape);
5645 =item B<path_info()>
5647 Returns additional path information from the script URL.
5648 E.G. fetching /cgi-bin/your_script/additional/stuff will
5649 result in $query->path_info() returning
5652 NOTE: The Microsoft Internet Information Server
5653 is broken with respect to additional path information. If
5654 you use the Perl DLL library, the IIS server will attempt to
5655 execute the additional path information as a Perl script.
5656 If you use the ordinary file associations mapping, the
5657 path information will be present in the environment,
5658 but incorrect. The best thing to do is to avoid using additional
5659 path information in CGI scripts destined for use with IIS.
5661 =item B<path_translated()>
5663 As per path_info() but returns the additional
5664 path information translated into a physical path, e.g.
5665 "/usr/local/etc/httpd/htdocs/additional/stuff".
5667 The Microsoft IIS is broken with respect to the translated
5670 =item B<remote_host()>
5672 Returns either the remote host name or IP address.
5673 if the former is unavailable.
5675 =item B<script_name()>
5676 Return the script name as a partial URL, for self-refering
5681 Return the URL of the page the browser was viewing
5682 prior to fetching your script. Not available for all
5685 =item B<auth_type ()>
5687 Return the authorization/verification method in use for this
5690 =item B<server_name ()>
5692 Returns the name of the server, usually the machine's host
5695 =item B<virtual_host ()>
5697 When using virtual hosts, returns the name of the host that
5698 the browser attempted to contact
5700 =item B<server_software ()>
5702 Returns the server software and version number.
5704 =item B<remote_user ()>
5706 Return the authorization/verification name used for user
5707 verification, if this script is protected.
5709 =item B<user_name ()>
5711 Attempt to obtain the remote user's name, using a variety
5712 of different techniques. This only works with older browsers
5713 such as Mosaic. Netscape does not reliably report the user
5716 =item B<request_method()>
5718 Returns the method used to access your script, usually
5719 one of 'POST', 'GET' or 'HEAD'.
5723 =head1 USING NPH SCRIPTS
5725 NPH, or "no-parsed-header", scripts bypass the server completely by
5726 sending the complete HTTP header directly to the browser. This has
5727 slight performance benefits, but is of most use for taking advantage
5728 of HTTP extensions that are not directly supported by your server,
5729 such as server push and PICS headers.
5731 Servers use a variety of conventions for designating CGI scripts as
5732 NPH. Many Unix servers look at the beginning of the script's name for
5733 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
5734 Internet Information Server, in contrast, try to decide whether a
5735 program is an NPH script by examining the first line of script output.
5738 CGI.pm supports NPH scripts with a special NPH mode. When in this
5739 mode, CGI.pm will output the necessary extra header information when
5740 the header() and redirect() methods are
5743 The Microsoft Internet Information Server requires NPH mode. As of version
5744 2.30, CGI.pm will automatically detect when the script is running under IIS
5745 and put itself into this mode. You do not need to do this manually, although
5746 it won't hurt anything if you do.
5748 There are a number of ways to put CGI.pm into NPH mode:
5752 =item In the B<use> statement
5754 Simply add the "-nph" pragmato the list of symbols to be imported into
5757 use CGI qw(:standard -nph)
5759 =item By calling the B<nph()> method:
5761 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
5765 =item By using B<-nph> parameters in the B<header()> and B<redirect()> statements:
5767 print $q->header(-nph=>1);
5773 CGI.pm provides three simple functions for producing multipart
5774 documents of the type needed to implement server push. These
5775 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
5776 import these into your namespace, you must import the ":push" set.
5777 You are also advised to put the script into NPH mode and to set $| to
5778 1 to avoid buffering problems.
5780 Here is a simple script that demonstrates server push:
5782 #!/usr/local/bin/perl
5783 use CGI qw/:push -nph/;
5785 print multipart_init(-boundary=>'----------------here we go!');
5787 print multipart_start(-type=>'text/plain'),
5788 "The current time is ",scalar(localtime),"\n",
5793 This script initializes server push by calling B<multipart_init()>.
5794 It then enters an infinite loop in which it begins a new multipart
5795 section by calling B<multipart_start()>, prints the current local time,
5796 and ends a multipart section with B<multipart_end()>. It then sleeps
5797 a second, and begins again.
5801 =item multipart_init()
5803 multipart_init(-boundary=>$boundary);
5805 Initialize the multipart system. The -boundary argument specifies
5806 what MIME boundary string to use to separate parts of the document.
5807 If not provided, CGI.pm chooses a reasonable boundary for you.
5809 =item multipart_start()
5811 multipart_start(-type=>$type)
5813 Start a new part of the multipart document using the specified MIME
5814 type. If not specified, text/html is assumed.
5816 =item multipart_end()
5820 End a part. You must remember to call multipart_end() once for each
5825 Users interested in server push applications should also have a look
5826 at the CGI::Push module.
5828 =head1 Avoiding Denial of Service Attacks
5830 A potential problem with CGI.pm is that, by default, it attempts to
5831 process form POSTings no matter how large they are. A wily hacker
5832 could attack your site by sending a CGI script a huge POST of many
5833 megabytes. CGI.pm will attempt to read the entire POST into a
5834 variable, growing hugely in size until it runs out of memory. While
5835 the script attempts to allocate the memory the system may slow down
5836 dramatically. This is a form of denial of service attack.
5838 Another possible attack is for the remote user to force CGI.pm to
5839 accept a huge file upload. CGI.pm will accept the upload and store it
5840 in a temporary directory even if your script doesn't expect to receive
5841 an uploaded file. CGI.pm will delete the file automatically when it
5842 terminates, but in the meantime the remote user may have filled up the
5843 server's disk space, causing problems for other programs.
5845 The best way to avoid denial of service attacks is to limit the amount
5846 of memory, CPU time and disk space that CGI scripts can use. Some Web
5847 servers come with built-in facilities to accomplish this. In other
5848 cases, you can use the shell I<limit> or I<ulimit>
5849 commands to put ceilings on CGI resource usage.
5852 CGI.pm also has some simple built-in protections against denial of
5853 service attacks, but you must activate them before you can use them.
5854 These take the form of two global variables in the CGI name space:
5858 =item B<$CGI::POST_MAX>
5860 If set to a non-negative integer, this variable puts a ceiling
5861 on the size of POSTings, in bytes. If CGI.pm detects a POST
5862 that is greater than the ceiling, it will immediately exit with an error
5863 message. This value will affect both ordinary POSTs and
5864 multipart POSTs, meaning that it limits the maximum size of file
5865 uploads as well. You should set this to a reasonably high
5866 value, such as 1 megabyte.
5868 =item B<$CGI::DISABLE_UPLOADS>
5870 If set to a non-zero value, this will disable file uploads
5871 completely. Other fill-out form values will work as usual.
5875 You can use these variables in either of two ways.
5879 =item B<1. On a script-by-script basis>
5881 Set the variable at the top of the script, right after the "use" statement:
5883 use CGI qw/:standard/;
5884 use CGI::Carp 'fatalsToBrowser';
5885 $CGI::POST_MAX=1024 * 100; # max 100K posts
5886 $CGI::DISABLE_UPLOADS = 1; # no uploads
5888 =item B<2. Globally for all scripts>
5890 Open up CGI.pm, find the definitions for $POST_MAX and
5891 $DISABLE_UPLOADS, and set them to the desired values. You'll
5892 find them towards the top of the file in a subroutine named
5893 initialize_globals().
5897 Since an attempt to send a POST larger than $POST_MAX bytes
5898 will cause a fatal error, you might want to use CGI::Carp to echo the
5899 fatal error message to the browser window as shown in the example
5900 above. Otherwise the remote user will see only a generic "Internal
5901 Server" error message. See the L<CGI::Carp> manual page for more
5904 =head1 COMPATIBILITY WITH CGI-LIB.PL
5906 To make it easier to port existing programs that use cgi-lib.pl
5907 the compatibility routine "ReadParse" is provided. Porting is
5911 require "cgi-lib.pl";
5913 print "The value of the antique is $in{antique}.\n";
5918 print "The value of the antique is $in{antique}.\n";
5920 CGI.pm's ReadParse() routine creates a tied variable named %in,
5921 which can be accessed to obtain the query variables. Like
5922 ReadParse, you can also provide your own variable. Infrequently
5923 used features of ReadParse, such as the creation of @in and $in
5924 variables, are not supported.
5926 Once you use ReadParse, you can retrieve the query object itself
5930 print $q->textfield(-name=>'wow',
5931 -value=>'does this really work?');
5933 This allows you to start using the more interesting features
5934 of CGI.pm without rewriting your old scripts from scratch.
5936 =head1 AUTHOR INFORMATION
5938 Copyright 1995-1997, Lincoln D. Stein. All rights reserved. It may
5939 be used and modified freely, but I do request that this copyright
5940 notice remain attached to the file. You may modify this module as you
5941 wish, but if you redistribute a modified version, please attach a note
5942 listing the modifications you have made.
5944 Address bug reports and comments to:
5945 lstein@genome.wi.mit.edu
5949 Thanks very much to:
5953 =item Matt Heffron (heffron@falstaff.css.beckman.com)
5955 =item James Taylor (james.taylor@srs.gov)
5957 =item Scott Anguish <sanguish@digifix.com>
5959 =item Mike Jewell (mlj3u@virginia.edu)
5961 =item Timothy Shimmin (tes@kbs.citri.edu.au)
5963 =item Joergen Haegg (jh@axis.se)
5965 =item Laurent Delfosse (delfosse@csgrad1.cs.wvu.edu)
5967 =item Richard Resnick (applepi1@aol.com)
5969 =item Craig Bishop (csb@barwonwater.vic.gov.au)
5971 =item Tony Curtis (tc@vcpc.univie.ac.at)
5973 =item Tim Bunce (Tim.Bunce@ig.co.uk)
5975 =item Tom Christiansen (tchrist@convex.com)
5977 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
5979 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
5981 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
5983 =item Stephen Dahmen (joyfire@inxpress.net)
5985 =item Ed Jordan (ed@fidalgo.net)
5987 =item David Alan Pisoni (david@cnation.com)
5989 =item Doug MacEachern (dougm@opengroup.org)
5991 =item Robin Houston (robin@oneworld.org)
5993 =item ...and many many more...
5995 for suggestions and bug fixes.
5999 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
6002 #!/usr/local/bin/perl
6008 print $query->header;
6009 print $query->start_html("Example CGI.pm Form");
6010 print "<H1> Example CGI.pm Form</H1>\n";
6011 &print_prompt($query);
6014 print $query->end_html;
6019 print $query->startform;
6020 print "<EM>What's your name?</EM><BR>";
6021 print $query->textfield('name');
6022 print $query->checkbox('Not my real name');
6024 print "<P><EM>Where can you find English Sparrows?</EM><BR>";
6025 print $query->checkbox_group(
6026 -name=>'Sparrow locations',
6027 -values=>[England,France,Spain,Asia,Hoboken],
6029 -defaults=>[England,Asia]);
6031 print "<P><EM>How far can they fly?</EM><BR>",
6032 $query->radio_group(
6034 -values=>['10 ft','1 mile','10 miles','real far'],
6035 -default=>'1 mile');
6037 print "<P><EM>What's your favorite color?</EM> ";
6038 print $query->popup_menu(-name=>'Color',
6039 -values=>['black','brown','red','yellow'],
6042 print $query->hidden('Reference','Monty Python and the Holy Grail');
6044 print "<P><EM>What have you got there?</EM><BR>";
6045 print $query->scrolling_list(
6046 -name=>'possessions',
6047 -values=>['A Coconut','A Grail','An Icon',
6048 'A Sword','A Ticket'],
6052 print "<P><EM>Any parting comments?</EM><BR>";
6053 print $query->textarea(-name=>'Comments',
6057 print "<P>",$query->reset;
6058 print $query->submit('Action','Shout');
6059 print $query->submit('Action','Scream');
6060 print $query->endform;
6068 print "<H2>Here are the current settings in this form</H2>";
6070 foreach $key ($query->param) {
6071 print "<STRONG>$key</STRONG> -> ";
6072 @values = $query->param($key);
6073 print join(", ",@values),"<BR>\n";
6080 <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
6081 <A HREF="/">Home Page</A>
6087 This module has grown large and monolithic. Furthermore it's doing many
6088 things, such as handling URLs, parsing CGI input, writing HTML, etc., that
6089 are also done in the LWP modules. It should be discarded in favor of
6090 the CGI::* modules, but somehow I continue to work on it.
6092 Note that the code is truly contorted in order to avoid spurious
6093 warnings when programs are run with the B<-w> switch.
6097 L<CGI::Carp>, L<URI::URL>, L<CGI::Request>, L<CGI::MiniSvr>,
6098 L<CGI::Base>, L<CGI::Form>, L<CGI::Apache>, L<CGI::Switch>,
6099 L<CGI::Push>, L<CGI::Fast>