5 # See the bottom of this file for the POD documentation. Search for the
8 # You can run this file through either pod2man or pod2html to produce pretty
9 # documentation in manual or html file format (these utilities are part of the
10 # Perl 5 distribution).
12 # Copyright 1995-1998 Lincoln D. Stein. All rights reserved.
13 # It may be used and modified freely, but I do request that this copyright
14 # notice remain attached to the file. You may modify this module as you
15 # wish, but if you redistribute a modified version, please attach a note
16 # listing the modifications you have made.
18 # The most recent version and complete docs are available at:
19 # http://stein.cshl.org/WWW/software/CGI/
21 $CGI::revision = '$Id: CGI.pm,v 1.51 2001/08/07 12:28:43 lstein Exp $';
24 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
25 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
26 # $TempFile::TMPDIRECTORY = '/usr/tmp';
27 use CGI::Util qw(rearrange make_attributes unescape escape expires);
29 use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
32 # >>>>> Here are some globals that you might want to adjust <<<<<<
33 sub initialize_globals {
34 # Set this to 1 to enable copious autoloader debugging messages
37 # Set this to 1 to generate XTML-compatible output
40 # Change this to the preferred DTD to print in start_html()
41 # or use default_dtd('text of DTD to use');
42 $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
43 'http://www.w3.org/TR/html4/loose.dtd' ] ;
45 # Set this to 1 to enable NOSTICKY scripts
47 # 1) use CGI qw(-nosticky)
48 # 2) $CGI::nosticky(1)
51 # Set this to 1 to enable NPH scripts
55 # 3) print header(-nph=>1)
58 # Set this to 1 to enable debugging from @ARGV
59 # Set to 2 to enable debugging from STDIN
62 # Set this to 1 to make the temporary files created
63 # during file uploads safe from prying eyes
65 # 1) use CGI qw(:private_tempfiles)
66 # 2) CGI::private_tempfiles(1);
67 $PRIVATE_TEMPFILES = 0;
69 # Set this to a positive value to limit the size of a POSTing
70 # to a certain number of bytes:
73 # Change this to 1 to disable uploads entirely:
76 # Automatically determined -- don't change
79 # Change this to 1 to suppress redundant HTTP headers
82 # separate the name=value pairs by semicolons rather than ampersands
83 $USE_PARAM_SEMICOLONS = 1;
85 # Do not include undefined params parsed from query string
86 # use CGI qw(-no_undef_params);
89 # Other globals that you shouldn't worry about.
95 undef %QUERY_FIELDNAMES;
97 # prevent complaints by mod_perl
101 # ------------------ START OF THE LIBRARY ------------
104 initialize_globals();
106 # FIGURE OUT THE OS WE'RE RUNNING UNDER
107 # Some systems support the $^O variable. If not
108 # available then require() the Config library
112 $OS = $Config::Config{'osname'};
115 if ($OS =~ /^MSWin/i) {
117 } elsif ($OS =~ /^VMS/i) {
119 } elsif ($OS =~ /^dos/i) {
121 } elsif ($OS =~ /^MacOS/i) {
123 } elsif ($OS =~ /^os2/i) {
125 } elsif ($OS =~ /^epoc/i) {
131 # Some OS logic. Binary mode enabled on DOS, NT and VMS
132 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin)/;
134 # This is the default class for the CGI object to use when all else fails.
135 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
137 # This is where to look for autoloaded routines.
138 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
140 # The path separator is a slash, backslash or semicolon, depending
143 UNIX=>'/', OS2=>'\\', EPOC=>'/',
144 WINDOWS=>'\\', DOS=>'\\', MACINTOSH=>':', VMS=>'/'
147 # This no longer seems to be necessary
148 # Turn on NPH scripts by default when running under IIS server!
149 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
150 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
152 # Turn on special checking for Doug MacEachern's modperl
153 if (exists $ENV{'GATEWAY_INTERFACE'}
155 ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//))
160 # Turn on special checking for ActiveState's PerlEx
161 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
163 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
164 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
165 # and sometimes CR). The most popular VMS web server
166 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
167 # use ASCII, so \015\012 means something different. I find this all
169 $EBCDIC = "\t" ne "\011";
178 if ($needs_binmode) {
179 $CGI::DefaultClass->binmode(main::STDOUT);
180 $CGI::DefaultClass->binmode(main::STDIN);
181 $CGI::DefaultClass->binmode(main::STDERR);
185 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
186 tt u i b blockquote pre img a address cite samp dfn html head
187 base body Link nextid title meta kbd start_html end_html
188 input Select option comment charset escapeHTML/],
189 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
190 embed basefont style span layer ilayer font frameset frame script small big/],
191 ':netscape'=>[qw/blink fontsize center/],
192 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
193 submit reset defaults radio_group popup_menu button autoEscape
194 scrolling_list image_button start_form end_form startform endform
195 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
196 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
197 raw_cookie request_method query_string Accept user_agent remote_host content_type
198 remote_addr referer server_name server_software server_port server_protocol
199 virtual_host remote_ident auth_type http
200 save_parameters restore_parameters param_fetch
201 remote_user user_name header redirect import_names put
202 Delete Delete_all url_param cgi_error/],
203 ':ssl' => [qw/https/],
204 ':imagemap' => [qw/Area Map/],
205 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
206 ':html' => [qw/:html2 :html3 :netscape/],
207 ':standard' => [qw/:html2 :html3 :form :cgi/],
208 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
209 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal/]
212 # to import symbols into caller
216 # This causes modules to clash.
220 $self->_setup_symbols(@_);
221 my ($callpack, $callfile, $callline) = caller;
223 # To allow overriding, search through the packages
224 # Till we find one in which the correct subroutine is defined.
225 my @packages = ($self,@{"$self\:\:ISA"});
226 foreach $sym (keys %EXPORT) {
228 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
229 foreach $pck (@packages) {
230 if (defined(&{"$pck\:\:$sym"})) {
235 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
241 $pack->_setup_symbols('-compile',@_);
246 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
248 return ($tag) unless $EXPORT_TAGS{$tag};
249 foreach (@{$EXPORT_TAGS{$tag}}) {
250 push(@r,&expand_tags($_));
256 # The new routine. This will check the current environment
257 # for an existing query string, and initialize itself, if so.
260 my($class,$initializer) = @_;
262 bless $self,ref $class || $class || $DefaultClass;
263 if ($MOD_PERL && defined Apache->request) {
264 Apache->request->register_cleanup(\&CGI::_reset_globals);
267 $self->_reset_globals if $PERLEX;
268 $self->init($initializer);
272 # We provide a DESTROY method so that the autoloader
273 # doesn't bother trying to find it.
277 # Returns the value(s)of a named parameter.
278 # If invoked in a list context, returns the
279 # entire list. Otherwise returns the first
280 # member of the list.
281 # If name is not provided, return a list of all
282 # the known parameters names available.
283 # If more than one argument is provided, the
284 # second and subsequent arguments are used to
285 # set the value of the parameter.
288 my($self,@p) = self_or_default(@_);
289 return $self->all_parameters unless @p;
290 my($name,$value,@other);
292 # For compatibility between old calling style and use_named_parameters() style,
293 # we have to special case for a single parameter present.
295 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
298 if (substr($p[0],0,1) eq '-') {
299 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
301 foreach ($value,@other) {
302 push(@values,$_) if defined($_);
305 # If values is provided, then we set it.
307 $self->add_parameter($name);
308 $self->{$name}=[@values];
314 return unless defined($name) && $self->{$name};
315 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
318 sub self_or_default {
319 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
320 unless (defined($_[0]) &&
321 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
323 $Q = $CGI::DefaultClass->new unless defined($Q);
326 return wantarray ? @_ : $Q;
330 local $^W=0; # prevent a warning
331 if (defined($_[0]) &&
332 (substr(ref($_[0]),0,3) eq 'CGI'
333 || UNIVERSAL::isa($_[0],'CGI'))) {
336 return ($DefaultClass,@_);
340 ########################################
341 # THESE METHODS ARE MORE OR LESS PRIVATE
342 # GO TO THE __DATA__ SECTION TO SEE MORE
344 ########################################
346 # Initialize the query object from the environment.
347 # If a parameter list is found, this object will be set
348 # to an associative array in which parameter names are keys
349 # and the values are stored as lists
350 # If a keyword list is found, this method creates a bogus
351 # parameter list with the single parameter 'keywords'.
354 my($self,$initializer) = @_;
355 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
358 # if we get called more than once, we want to initialize
359 # ourselves from the original query (which may be gone
360 # if it was read from STDIN originally.)
361 if (defined(@QUERY_PARAM) && !defined($initializer)) {
362 foreach (@QUERY_PARAM) {
363 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
365 $self->charset($QUERY_CHARSET);
366 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
370 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
371 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
373 $fh = to_filehandle($initializer) if $initializer;
375 # set charset to the safe ISO-8859-1
376 $self->charset('ISO-8859-1');
380 # avoid unreasonably large postings
381 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
382 $self->cgi_error("413 Request entity too large");
386 # Process multipart postings, but only if the initializer is
389 && defined($ENV{'CONTENT_TYPE'})
390 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
391 && !defined($initializer)
393 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
394 $self->read_multipart($boundary,$content_length);
398 # If initializer is defined, then read parameters
400 if (defined($initializer)) {
401 if (UNIVERSAL::isa($initializer,'CGI')) {
402 $query_string = $initializer->query_string;
405 if (ref($initializer) && ref($initializer) eq 'HASH') {
406 foreach (keys %$initializer) {
407 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
412 if (defined($fh) && ($fh ne '')) {
418 # massage back into standard format
419 if ("@lines" =~ /=/) {
420 $query_string=join("&",@lines);
422 $query_string=join("+",@lines);
427 # last chance -- treat it as a string
428 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
429 $query_string = $initializer;
434 # If method is GET or HEAD, fetch the query from
436 if ($meth=~/^(GET|HEAD)$/) {
438 $query_string = Apache->request->args;
440 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
441 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
446 if ($meth eq 'POST') {
447 $self->read_from_client(\*STDIN,\$query_string,$content_length,0)
448 if $content_length > 0;
449 # Some people want to have their cake and eat it too!
450 # Uncomment this line to have the contents of the query string
451 # APPENDED to the POST data.
452 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
456 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
457 # Check the command line and then the standard input for data.
458 # We use the shellwords package in order to behave the way that
459 # UN*X programmers expect.
460 $query_string = read_from_cmdline() if $DEBUG;
463 # We now have the query string in hand. We do slightly
464 # different things for keyword lists and parameter lists.
465 if (defined $query_string && length $query_string) {
466 if ($query_string =~ /[&=;]/) {
467 $self->parse_params($query_string);
469 $self->add_parameter('keywords');
470 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
474 # Special case. Erase everything if there is a field named
476 if ($self->param('.defaults')) {
480 # Associative array containing our defined fieldnames
481 $self->{'.fieldnames'} = {};
482 foreach ($self->param('.cgifields')) {
483 $self->{'.fieldnames'}->{$_}++;
486 # Clear out our default submission button flag if present
487 $self->delete('.submit');
488 $self->delete('.cgifields');
490 $self->save_request unless $initializer;
493 # FUNCTIONS TO OVERRIDE:
494 # Turn a string into a filehandle
497 return undef unless $thingy;
498 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
499 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
502 while (my $package = caller($caller++)) {
503 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
504 return $tmp if defined(fileno($tmp));
510 # send output to the browser
512 my($self,@p) = self_or_default(@_);
516 # print to standard output (for overriding in mod_perl)
522 # get/set last cgi_error
524 my ($self,$err) = self_or_default(@_);
525 $self->{'.cgi_error'} = $err if defined $err;
526 return $self->{'.cgi_error'};
531 # We're going to play with the package globals now so that if we get called
532 # again, we initialize ourselves in exactly the same way. This allows
533 # us to have several of these objects.
534 @QUERY_PARAM = $self->param; # save list of parameters
535 foreach (@QUERY_PARAM) {
536 next unless defined $_;
537 $QUERY_PARAM{$_}=$self->{$_};
539 $QUERY_CHARSET = $self->charset;
540 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
544 my($self,$tosplit) = @_;
545 my(@pairs) = split(/[&;]/,$tosplit);
548 ($param,$value) = split('=',$_,2);
549 next if $NO_UNDEF_PARAMS and not defined $value;
550 $value = '' unless defined $value;
551 $param = unescape($param);
552 $value = unescape($value);
553 $self->add_parameter($param);
554 push (@{$self->{$param}},$value);
560 return unless defined $param;
561 push (@{$self->{'.parameters'}},$param)
562 unless defined($self->{$param});
567 return () unless defined($self) && $self->{'.parameters'};
568 return () unless @{$self->{'.parameters'}};
569 return @{$self->{'.parameters'}};
572 # put a filehandle into binary mode (DOS)
574 CORE::binmode($_[1]);
578 my ($self,$tagname) = @_;
583 (substr(ref(\$_[0]),0,3) eq 'CGI' ||
584 UNIVERSAL::isa(\$_[0],'CGI')));
586 if (ref(\$_[0]) && ref(\$_[0]) eq 'HASH') {
587 my(\@attr) = make_attributes(shift()||undef,1);
588 \$attr = " \@attr" if \@attr;
591 if ($tagname=~/start_(\w+)/i) {
592 $func .= qq! return "<\L$1\E\$attr>";} !;
593 } elsif ($tagname=~/end_(\w+)/i) {
594 $func .= qq! return "<\L/$1\E>"; } !;
597 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@_;
598 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
599 my \@result = map { "\$tag\$_\$untag" }
600 (ref(\$_[0]) eq 'ARRAY') ? \@{\$_[0]} : "\@_";
608 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
609 my $func = &_compile;
614 my($func) = $AUTOLOAD;
615 my($pack,$func_name);
617 local($1,$2); # this fixes an obscure variable suicide problem.
618 $func=~/(.+)::([^:]+)$/;
619 ($pack,$func_name) = ($1,$2);
620 $pack=~s/::SUPER$//; # fix another obscure problem
621 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
622 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
624 my($sub) = \%{"$pack\:\:SUBS"};
626 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
627 eval "package $pack; $$auto";
628 croak("$AUTOLOAD: $@") if $@;
629 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
631 my($code) = $sub->{$func_name};
633 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
635 (my $base = $func_name) =~ s/^(start_|end_)//i;
636 if ($EXPORT{':any'} ||
639 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
640 && $EXPORT_OK{$base}) {
641 $code = $CGI::DefaultClass->_make_tag_func($func_name);
644 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
645 eval "package $pack; $code";
648 croak("$AUTOLOAD: $@");
651 CORE::delete($sub->{$func_name}); #free storage
652 return "$pack\:\:$func_name";
655 sub _reset_globals { initialize_globals(); }
661 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
662 $NPH++, next if /^[:-]nph$/;
663 $NOSTICKY++, next if /^[:-]nosticky$/;
664 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
665 $DEBUG=2, next if /^[:-][Dd]ebug$/;
666 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
667 $XHTML++, next if /^[:-]xhtml$/;
668 $XHTML=0, next if /^[:-]no_?xhtml$/;
669 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
670 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
671 $EXPORT{$_}++, next if /^[:-]any$/;
672 $compile++, next if /^[:-]compile$/;
673 $NO_UNDEF_PARAMS++, next if /^[:-]no_undef_params$/;
675 # This is probably extremely evil code -- to be deleted some day.
676 if (/^[-]autoload$/) {
677 my($pkg) = caller(1);
678 *{"${pkg}::AUTOLOAD"} = sub {
679 my($routine) = $AUTOLOAD;
680 $routine =~ s/^.*::/CGI::/;
686 foreach (&expand_tags($_)) {
687 tr/a-zA-Z0-9_//cd; # don't allow weird function names
691 _compile_all(keys %EXPORT) if $compile;
695 my ($self,$charset) = self_or_default(@_);
696 $self->{'.charset'} = $charset if defined $charset;
700 ###############################################################################
701 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
702 ###############################################################################
703 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
704 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
708 'URL_ENCODED'=> <<'END_OF_FUNC',
709 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
712 'MULTIPART' => <<'END_OF_FUNC',
713 sub MULTIPART { 'multipart/form-data'; }
716 'SERVER_PUSH' => <<'END_OF_FUNC',
717 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
720 'new_MultipartBuffer' => <<'END_OF_FUNC',
721 # Create a new multipart buffer
722 sub new_MultipartBuffer {
723 my($self,$boundary,$length,$filehandle) = @_;
724 return MultipartBuffer->new($self,$boundary,$length,$filehandle);
728 'read_from_client' => <<'END_OF_FUNC',
729 # Read data from a file handle
730 sub read_from_client {
731 my($self, $fh, $buff, $len, $offset) = @_;
732 local $^W=0; # prevent a warning
733 return undef unless defined($fh);
734 return read($fh, $$buff, $len, $offset);
738 'delete' => <<'END_OF_FUNC',
740 # Deletes the named parameter entirely.
743 my($self,@p) = self_or_default(@_);
744 my($name) = rearrange([NAME],@p);
745 CORE::delete $self->{$name};
746 CORE::delete $self->{'.fieldnames'}->{$name};
747 @{$self->{'.parameters'}}=grep($_ ne $name,$self->param());
748 return wantarray ? () : undef;
752 #### Method: import_names
753 # Import all parameters into the given namespace.
754 # Assumes namespace 'Q' if not specified
756 'import_names' => <<'END_OF_FUNC',
758 my($self,$namespace,$delete) = self_or_default(@_);
759 $namespace = 'Q' unless defined($namespace);
760 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
761 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
762 # can anyone find an easier way to do this?
763 foreach (keys %{"${namespace}::"}) {
764 local *symbol = "${namespace}::${_}";
770 my($param,@value,$var);
771 foreach $param ($self->param) {
772 # protect against silly names
773 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
774 $var =~ s/^(?=\d)/_/;
775 local *symbol = "${namespace}::$var";
776 @value = $self->param($param);
783 #### Method: keywords
784 # Keywords acts a bit differently. Calling it in a list context
785 # returns the list of keywords.
786 # Calling it in a scalar context gives you the size of the list.
788 'keywords' => <<'END_OF_FUNC',
790 my($self,@values) = self_or_default(@_);
791 # If values is provided, then we set it.
792 $self->{'keywords'}=[@values] if @values;
793 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
798 # These are some tie() interfaces for compatibility
799 # with Steve Brenner's cgi-lib.pl routines
800 'Vars' => <<'END_OF_FUNC',
805 return %in if wantarray;
810 # These are some tie() interfaces for compatibility
811 # with Steve Brenner's cgi-lib.pl routines
812 'ReadParse' => <<'END_OF_FUNC',
822 return scalar(keys %in);
826 'PrintHeader' => <<'END_OF_FUNC',
828 my($self) = self_or_default(@_);
829 return $self->header();
833 'HtmlTop' => <<'END_OF_FUNC',
835 my($self,@p) = self_or_default(@_);
836 return $self->start_html(@p);
840 'HtmlBot' => <<'END_OF_FUNC',
842 my($self,@p) = self_or_default(@_);
843 return $self->end_html(@p);
847 'SplitParam' => <<'END_OF_FUNC',
850 my (@params) = split ("\0", $param);
851 return (wantarray ? @params : $params[0]);
855 'MethGet' => <<'END_OF_FUNC',
857 return request_method() eq 'GET';
861 'MethPost' => <<'END_OF_FUNC',
863 return request_method() eq 'POST';
867 'TIEHASH' => <<'END_OF_FUNC',
869 return $_[1] if defined $_[1];
870 return $Q ||= new shift;
874 'STORE' => <<'END_OF_FUNC',
879 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
880 $self->param(-name=>$tag,-value=>\@vals);
884 'FETCH' => <<'END_OF_FUNC',
886 return $_[0] if $_[1] eq 'CGI';
887 return undef unless defined $_[0]->param($_[1]);
888 return join("\0",$_[0]->param($_[1]));
892 'FIRSTKEY' => <<'END_OF_FUNC',
894 $_[0]->{'.iterator'}=0;
895 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
899 'NEXTKEY' => <<'END_OF_FUNC',
901 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
905 'EXISTS' => <<'END_OF_FUNC',
907 exists $_[0]->{$_[1]};
911 'DELETE' => <<'END_OF_FUNC',
913 $_[0]->delete($_[1]);
917 'CLEAR' => <<'END_OF_FUNC',
925 # Append a new value to an existing query
930 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
931 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
933 $self->add_parameter($name);
934 push(@{$self->{$name}},@values);
936 return $self->param($name);
940 #### Method: delete_all
941 # Delete all parameters
943 'delete_all' => <<'EOF',
945 my($self) = self_or_default(@_);
952 my($self,@p) = self_or_default(@_);
957 'Delete_all' => <<'EOF',
959 my($self,@p) = self_or_default(@_);
960 $self->delete_all(@p);
964 #### Method: autoescape
965 # If you want to turn off the autoescaping features,
966 # call this method with undef as the argument
967 'autoEscape' => <<'END_OF_FUNC',
969 my($self,$escape) = self_or_default(@_);
970 $self->{'dontescape'}=!$escape;
976 # Return the current version
978 'version' => <<'END_OF_FUNC',
984 #### Method: url_param
985 # Return a parameter in the QUERY_STRING, regardless of
986 # whether this was a POST or a GET
988 'url_param' => <<'END_OF_FUNC',
990 my ($self,@p) = self_or_default(@_);
991 my $name = shift(@p);
992 return undef unless exists($ENV{QUERY_STRING});
993 unless (exists($self->{'.url_param'})) {
994 $self->{'.url_param'}={}; # empty hash
995 if ($ENV{QUERY_STRING} =~ /=/) {
996 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
999 ($param,$value) = split('=',$_,2);
1000 $param = unescape($param);
1001 $value = unescape($value);
1002 push(@{$self->{'.url_param'}->{$param}},$value);
1005 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1008 return keys %{$self->{'.url_param'}} unless defined($name);
1009 return () unless $self->{'.url_param'}->{$name};
1010 return wantarray ? @{$self->{'.url_param'}->{$name}}
1011 : $self->{'.url_param'}->{$name}->[0];
1016 # Returns a string in which all the known parameter/value
1017 # pairs are represented as nested lists, mainly for the purposes
1020 'Dump' => <<'END_OF_FUNC',
1022 my($self) = self_or_default(@_);
1023 my($param,$value,@result);
1024 return '<UL></UL>' unless $self->param;
1025 push(@result,"<UL>");
1026 foreach $param ($self->param) {
1027 my($name)=$self->escapeHTML($param);
1028 push(@result,"<LI><STRONG>$param</STRONG>");
1029 push(@result,"<UL>");
1030 foreach $value ($self->param($param)) {
1031 $value = $self->escapeHTML($value);
1032 $value =~ s/\n/<BR>\n/g;
1033 push(@result,"<LI>$value");
1035 push(@result,"</UL>");
1037 push(@result,"</UL>");
1038 return join("\n",@result);
1042 #### Method as_string
1044 # synonym for "dump"
1046 'as_string' => <<'END_OF_FUNC',
1053 # Write values out to a filehandle in such a way that they can
1054 # be reinitialized by the filehandle form of the new() method
1056 'save' => <<'END_OF_FUNC',
1058 my($self,$filehandle) = self_or_default(@_);
1059 $filehandle = to_filehandle($filehandle);
1061 local($,) = ''; # set print field separator back to a sane value
1062 local($\) = ''; # set output line separator to a sane value
1063 foreach $param ($self->param) {
1064 my($escaped_param) = escape($param);
1066 foreach $value ($self->param($param)) {
1067 print $filehandle "$escaped_param=",escape("$value"),"\n";
1070 foreach (keys %{$self->{'.fieldnames'}}) {
1071 print $filehandle ".cgifields=",escape("$_"),"\n";
1073 print $filehandle "=\n"; # end of record
1078 #### Method: save_parameters
1079 # An alias for save() that is a better name for exportation.
1080 # Only intended to be used with the function (non-OO) interface.
1082 'save_parameters' => <<'END_OF_FUNC',
1083 sub save_parameters {
1085 return save(to_filehandle($fh));
1089 #### Method: restore_parameters
1090 # A way to restore CGI parameters from an initializer.
1091 # Only intended to be used with the function (non-OO) interface.
1093 'restore_parameters' => <<'END_OF_FUNC',
1094 sub restore_parameters {
1095 $Q = $CGI::DefaultClass->new(@_);
1099 #### Method: multipart_init
1100 # Return a Content-Type: style header for server-push
1101 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1103 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1104 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1106 'multipart_init' => <<'END_OF_FUNC',
1107 sub multipart_init {
1108 my($self,@p) = self_or_default(@_);
1109 my($boundary,@other) = rearrange([BOUNDARY],@p);
1110 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1111 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1112 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1113 $type = SERVER_PUSH($boundary);
1114 return $self->header(
1117 (map { split "=", $_, 2 } @other),
1118 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1123 #### Method: multipart_start
1124 # Return a Content-Type: style header for server-push, start of section
1126 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1127 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1129 'multipart_start' => <<'END_OF_FUNC',
1130 sub multipart_start {
1132 my($self,@p) = self_or_default(@_);
1133 my($type,@other) = rearrange([TYPE],@p);
1134 $type = $type || 'text/html';
1135 push(@header,"Content-Type: $type");
1137 # rearrange() was designed for the HTML portion, so we
1138 # need to fix it up a little.
1140 next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1141 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1143 push(@header,@other);
1144 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1150 #### Method: multipart_end
1151 # Return a MIME boundary separator for server-push, end of section
1153 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1156 'multipart_end' => <<'END_OF_FUNC',
1158 my($self,@p) = self_or_default(@_);
1159 return $self->{'separator'};
1164 #### Method: multipart_final
1165 # Return a MIME boundary separator for server-push, end of all sections
1167 # Contributed by Andrew Benham (adsb@bigfoot.com)
1169 'multipart_final' => <<'END_OF_FUNC',
1170 sub multipart_final {
1171 my($self,@p) = self_or_default(@_);
1172 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1178 # Return a Content-Type: style header
1181 'header' => <<'END_OF_FUNC',
1183 my($self,@p) = self_or_default(@_);
1186 return undef if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1188 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,@other) =
1189 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1190 'STATUS',['COOKIE','COOKIES'],'TARGET',
1191 'EXPIRES','NPH','CHARSET',
1195 if (defined $charset) {
1196 $self->charset($charset);
1198 $charset = $self->charset;
1201 # rearrange() was designed for the HTML portion, so we
1202 # need to fix it up a little.
1204 next unless my($header,$value) = /([^\s=]+)=\"?(.+?)\"?$/;
1205 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1206 $header = ucfirst($header);
1209 $type ||= 'text/html' unless defined($type);
1210 $type .= "; charset=$charset" if $type ne '' and $type =~ m!^text/! and $type !~ /\bcharset\b/;
1212 # Maybe future compatibility. Maybe not.
1213 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1214 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1215 push(@header,"Server: " . &server_software()) if $nph;
1217 push(@header,"Status: $status") if $status;
1218 push(@header,"Window-Target: $target") if $target;
1219 # push all the cookies -- there may be several
1221 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1223 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1224 push(@header,"Set-Cookie: $cs") if $cs ne '';
1227 # if the user indicates an expiration time, then we need
1228 # both an Expires and a Date header (so that the browser is
1230 push(@header,"Expires: " . expires($expires,'http'))
1232 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1233 push(@header,"Pragma: no-cache") if $self->cache();
1234 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1235 push(@header,map {ucfirst $_} @other);
1236 push(@header,"Content-Type: $type") if $type ne '';
1238 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1239 if ($MOD_PERL and not $nph) {
1240 my $r = Apache->request;
1241 $r->send_cgi_header($header);
1250 # Control whether header() will produce the no-cache
1253 'cache' => <<'END_OF_FUNC',
1255 my($self,$new_value) = self_or_default(@_);
1256 $new_value = '' unless $new_value;
1257 if ($new_value ne '') {
1258 $self->{'cache'} = $new_value;
1260 return $self->{'cache'};
1265 #### Method: redirect
1266 # Return a Location: style header
1269 'redirect' => <<'END_OF_FUNC',
1271 my($self,@p) = self_or_default(@_);
1272 my($url,$target,$cookie,$nph,@other) = rearrange([[LOCATION,URI,URL],TARGET,COOKIE,NPH],@p);
1273 $url ||= $self->self_url;
1275 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1277 '-Status'=>'302 Moved',
1280 unshift(@o,'-Target'=>$target) if $target;
1281 unshift(@o,'-Cookie'=>$cookie) if $cookie;
1282 unshift(@o,'-Type'=>'');
1283 return $self->header(@o);
1288 #### Method: start_html
1289 # Canned HTML header
1292 # $title -> (optional) The title for this HTML document (-title)
1293 # $author -> (optional) e-mail address of the author (-author)
1294 # $base -> (optional) if set to true, will enter the BASE address of this document
1295 # for resolving relative references (-base)
1296 # $xbase -> (optional) alternative base at some remote location (-xbase)
1297 # $target -> (optional) target window to load all links into (-target)
1298 # $script -> (option) Javascript code (-script)
1299 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1300 # $meta -> (optional) Meta information tags
1301 # $head -> (optional) any other elements you'd like to incorporate into the <HEAD> tag
1302 # (a scalar or array ref)
1303 # $style -> (optional) reference to an external style sheet
1304 # @other -> (optional) any other named parameters you'd like to incorporate into
1307 'start_html' => <<'END_OF_FUNC',
1309 my($self,@p) = &self_or_default(@_);
1310 my($title,$author,$base,$xbase,$script,$noscript,$target,$meta,$head,$style,$dtd,$lang,@other) =
1311 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD,LANG],@p);
1313 # strangely enough, the title needs to be escaped as HTML
1314 # while the author needs to be escaped as a URL
1315 $title = $self->escapeHTML($title || 'Untitled Document');
1316 $author = $self->escape($author);
1318 my(@result,$xml_dtd);
1320 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1321 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1323 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1326 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1329 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1330 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1331 push @result,q(<?xml version="1.0" encoding="utf-8"?>) if $xml_dtd;
1333 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1334 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t"$dtd->[1]">));
1336 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1338 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang"><head><title>$title</title>)
1339 : qq(<html lang="$lang"><head><title>$title</title>));
1340 if (defined $author) {
1341 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1342 : "<link rev=\"made\" href=\"mailto:$author\">");
1345 if ($base || $xbase || $target) {
1346 my $href = $xbase || $self->url('-path'=>1);
1347 my $t = $target ? qq/ target="$target"/ : '';
1348 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1351 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1352 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1353 : qq(<meta name="$_" content="$meta->{$_}">)); }
1356 push(@result,ref($head) ? @$head : $head) if $head;
1358 # handle the infrequently-used -style and -script parameters
1359 push(@result,$self->_style($style)) if defined $style;
1360 push(@result,$self->_script($script)) if defined $script;
1362 # handle -noscript parameter
1363 push(@result,<<END) if $noscript;
1369 my($other) = @other ? " @other" : '';
1370 push(@result,"</head><body$other>");
1371 return join("\n",@result);
1376 # internal method for generating a CSS style section
1378 '_style' => <<'END_OF_FUNC',
1380 my ($self,$style) = @_;
1382 my $type = 'text/css';
1384 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1385 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1388 my($src,$code,$stype,@other) =
1389 rearrange([SRC,CODE,TYPE],
1390 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1391 ref($style) eq 'ARRAY' ? @$style : %$style);
1392 $type = $stype if $stype;
1393 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1394 { # If it is, push a LINK tag for each one.
1395 foreach $src (@$src)
1397 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1398 : qq(<link rel="stylesheet" type="$type" href="$src">/)) if $src;
1402 { # Otherwise, push the single -src, if it exists.
1403 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" />)
1404 : qq(<link rel="stylesheet" type="$type" href="$src">)
1407 push(@result,style({'type'=>$type},"$cdata_start\n$code\n$cdata_end")) if $code;
1409 push(@result,style({'type'=>$type},"$cdata_start\n$style\n$cdata_end"));
1415 '_script' => <<'END_OF_FUNC',
1417 my ($self,$script) = @_;
1420 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1421 foreach $script (@scripts) {
1422 my($src,$code,$language);
1423 if (ref($script)) { # script is a hash
1424 ($src,$code,$language, $type) =
1425 rearrange([SRC,CODE,LANGUAGE,TYPE],
1426 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1427 ref($script) eq 'ARRAY' ? @$script : %$script);
1428 # User may not have specified language
1429 $language ||= 'JavaScript';
1430 unless (defined $type) {
1431 $type = lc $language;
1432 # strip '1.2' from 'javascript1.2'
1433 $type =~ s/^(\D+).*$/text\/$1/;
1436 ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
1439 my $comment = '//'; # javascript by default
1440 $comment = '#' if $type=~/perl|tcl/i;
1441 $comment = "'" if $type=~/vbscript/i;
1443 my $cdata_start = "\n<!-- Hide script\n";
1444 $cdata_start .= "$comment<![CDATA[\n" if $XHTML;
1445 my $cdata_end = $XHTML ? "\n$comment]]>" : $comment;
1446 $cdata_end .= " End script hiding -->\n";
1449 push(@satts,'src'=>$src) if $src;
1450 push(@satts,'language'=>$language);
1451 push(@satts,'type'=>$type);
1452 $code = "$cdata_start$code$cdata_end" if defined $code;
1453 push(@result,script({@satts},$code || ''));
1459 #### Method: end_html
1460 # End an HTML document.
1461 # Trivial method for completeness. Just returns "</BODY>"
1463 'end_html' => <<'END_OF_FUNC',
1465 return "</body></html>";
1470 ################################
1471 # METHODS USED IN BUILDING FORMS
1472 ################################
1474 #### Method: isindex
1475 # Just prints out the isindex tag.
1477 # $action -> optional URL of script to run
1479 # A string containing a <ISINDEX> tag
1480 'isindex' => <<'END_OF_FUNC',
1482 my($self,@p) = self_or_default(@_);
1483 my($action,@other) = rearrange([ACTION],@p);
1484 $action = qq/action="$action"/ if $action;
1485 my($other) = @other ? " @other" : '';
1486 return $XHTML ? "<isindex $action$other />" : "<isindex $action$other>";
1491 #### Method: startform
1494 # $method -> optional submission method to use (GET or POST)
1495 # $action -> optional URL of script to run
1496 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1497 'startform' => <<'END_OF_FUNC',
1499 my($self,@p) = self_or_default(@_);
1501 my($method,$action,$enctype,@other) =
1502 rearrange([METHOD,ACTION,ENCTYPE],@p);
1504 $method = lc($method) || 'post';
1505 $enctype = $enctype || &URL_ENCODED;
1506 unless (defined $action) {
1507 $action = $self->url(-absolute=>1,-path=>1);
1508 $action .= "?$ENV{QUERY_STRING}" if $ENV{QUERY_STRING};
1510 $action = qq(action="$action");
1511 my($other) = @other ? " @other" : '';
1512 $self->{'.parametersToAdd'}={};
1513 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1518 #### Method: start_form
1519 # synonym for startform
1520 'start_form' => <<'END_OF_FUNC',
1526 'end_multipart_form' => <<'END_OF_FUNC',
1527 sub end_multipart_form {
1532 #### Method: start_multipart_form
1533 # synonym for startform
1534 'start_multipart_form' => <<'END_OF_FUNC',
1535 sub start_multipart_form {
1536 my($self,@p) = self_or_default(@_);
1537 if (defined($param[0]) && substr($param[0],0,1) eq '-') {
1539 $p{'-enctype'}=&MULTIPART;
1540 return $self->startform(%p);
1542 my($method,$action,@other) =
1543 rearrange([METHOD,ACTION],@p);
1544 return $self->startform($method,$action,&MULTIPART,@other);
1550 #### Method: endform
1552 'endform' => <<'END_OF_FUNC',
1554 my($self,@p) = self_or_default(@_);
1556 return wantarray ? ("</form>") : "\n</form>";
1558 return wantarray ? ($self->get_fields,"</form>") :
1559 $self->get_fields ."\n</form>";
1565 #### Method: end_form
1566 # synonym for endform
1567 'end_form' => <<'END_OF_FUNC',
1574 '_textfield' => <<'END_OF_FUNC',
1576 my($self,$tag,@p) = self_or_default(@_);
1577 my($name,$default,$size,$maxlength,$override,@other) =
1578 rearrange([NAME,[DEFAULT,VALUE],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1580 my $current = $override ? $default :
1581 (defined($self->param($name)) ? $self->param($name) : $default);
1583 $current = defined($current) ? $self->escapeHTML($current,1) : '';
1584 $name = defined($name) ? $self->escapeHTML($name) : '';
1585 my($s) = defined($size) ? qq/ size="$size"/ : '';
1586 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1587 my($other) = @other ? " @other" : '';
1588 # this entered at cristy's request to fix problems with file upload fields
1589 # and WebTV -- not sure it won't break stuff
1590 my($value) = $current ne '' ? qq(value="$current") : '';
1591 return $XHTML ? qq(<input type="$tag" name="$name" $value$s$m$other />)
1592 : qq/<input type="$tag" name="$name" $value$s$m$other>/;
1596 #### Method: textfield
1598 # $name -> Name of the text field
1599 # $default -> Optional default value of the field if not
1601 # $size -> Optional width of field in characaters.
1602 # $maxlength -> Optional maximum number of characters.
1604 # A string containing a <INPUT TYPE="text"> field
1606 'textfield' => <<'END_OF_FUNC',
1608 my($self,@p) = self_or_default(@_);
1609 $self->_textfield('text',@p);
1614 #### Method: filefield
1616 # $name -> Name of the file upload field
1617 # $size -> Optional width of field in characaters.
1618 # $maxlength -> Optional maximum number of characters.
1620 # A string containing a <INPUT TYPE="text"> field
1622 'filefield' => <<'END_OF_FUNC',
1624 my($self,@p) = self_or_default(@_);
1625 $self->_textfield('file',@p);
1630 #### Method: password
1631 # Create a "secret password" entry field
1633 # $name -> Name of the field
1634 # $default -> Optional default value of the field if not
1636 # $size -> Optional width of field in characters.
1637 # $maxlength -> Optional maximum characters that can be entered.
1639 # A string containing a <INPUT TYPE="password"> field
1641 'password_field' => <<'END_OF_FUNC',
1642 sub password_field {
1643 my ($self,@p) = self_or_default(@_);
1644 $self->_textfield('password',@p);
1648 #### Method: textarea
1650 # $name -> Name of the text field
1651 # $default -> Optional default value of the field if not
1653 # $rows -> Optional number of rows in text area
1654 # $columns -> Optional number of columns in text area
1656 # A string containing a <TEXTAREA></TEXTAREA> tag
1658 'textarea' => <<'END_OF_FUNC',
1660 my($self,@p) = self_or_default(@_);
1662 my($name,$default,$rows,$cols,$override,@other) =
1663 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1665 my($current)= $override ? $default :
1666 (defined($self->param($name)) ? $self->param($name) : $default);
1668 $name = defined($name) ? $self->escapeHTML($name) : '';
1669 $current = defined($current) ? $self->escapeHTML($current) : '';
1670 my($r) = $rows ? " rows=$rows" : '';
1671 my($c) = $cols ? " cols=$cols" : '';
1672 my($other) = @other ? " @other" : '';
1673 return qq{<textarea name="$name"$r$c$other>$current</textarea>};
1679 # Create a javascript button.
1681 # $name -> (optional) Name for the button. (-name)
1682 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1683 # $onclick -> (optional) Text of the JavaScript to run when the button is
1686 # A string containing a <INPUT TYPE="button"> tag
1688 'button' => <<'END_OF_FUNC',
1690 my($self,@p) = self_or_default(@_);
1692 my($label,$value,$script,@other) = rearrange([NAME,[VALUE,LABEL],
1693 [ONCLICK,SCRIPT]],@p);
1695 $label=$self->escapeHTML($label);
1696 $value=$self->escapeHTML($value,1);
1697 $script=$self->escapeHTML($script);
1700 $name = qq/ name="$label"/ if $label;
1701 $value = $value || $label;
1703 $val = qq/ value="$value"/ if $value;
1704 $script = qq/ onclick="$script"/ if $script;
1705 my($other) = @other ? " @other" : '';
1706 return $XHTML ? qq(<input type="button"$name$val$script$other />)
1707 : qq/<input type="button"$name$val$script$other>/;
1713 # Create a "submit query" button.
1715 # $name -> (optional) Name for the button.
1716 # $value -> (optional) Value of the button when selected (also doubles as label).
1717 # $label -> (optional) Label printed on the button(also doubles as the value).
1719 # A string containing a <INPUT TYPE="submit"> tag
1721 'submit' => <<'END_OF_FUNC',
1723 my($self,@p) = self_or_default(@_);
1725 my($label,$value,@other) = rearrange([NAME,[VALUE,LABEL]],@p);
1727 $label=$self->escapeHTML($label);
1728 $value=$self->escapeHTML($value,1);
1730 my($name) = ' name=".submit"' unless $NOSTICKY;
1731 $name = qq/ name="$label"/ if defined($label);
1732 $value = defined($value) ? $value : $label;
1734 $val = qq/ value="$value"/ if defined($value);
1735 my($other) = @other ? " @other" : '';
1736 return $XHTML ? qq(<input type="submit"$name$val$other />)
1737 : qq/<input type="submit"$name$val$other>/;
1743 # Create a "reset" button.
1745 # $name -> (optional) Name for the button.
1747 # A string containing a <INPUT TYPE="reset"> tag
1749 'reset' => <<'END_OF_FUNC',
1751 my($self,@p) = self_or_default(@_);
1752 my($label,@other) = rearrange([NAME],@p);
1753 $label=$self->escapeHTML($label);
1754 my($value) = defined($label) ? qq/ value="$label"/ : '';
1755 my($other) = @other ? " @other" : '';
1756 return $XHTML ? qq(<input type="reset"$value$other />)
1757 : qq/<input type="reset"$value$other>/;
1762 #### Method: defaults
1763 # Create a "defaults" button.
1765 # $name -> (optional) Name for the button.
1767 # A string containing a <INPUT TYPE="submit" NAME=".defaults"> tag
1769 # Note: this button has a special meaning to the initialization script,
1770 # and tells it to ERASE the current query string so that your defaults
1773 'defaults' => <<'END_OF_FUNC',
1775 my($self,@p) = self_or_default(@_);
1777 my($label,@other) = rearrange([[NAME,VALUE]],@p);
1779 $label=$self->escapeHTML($label,1);
1780 $label = $label || "Defaults";
1781 my($value) = qq/ value="$label"/;
1782 my($other) = @other ? " @other" : '';
1783 return $XHTML ? qq(<input type="submit" name=".defaults"$value$other />)
1784 : qq/<input type="submit" NAME=".defaults"$value$other>/;
1789 #### Method: comment
1790 # Create an HTML <!-- comment -->
1791 # Parameters: a string
1792 'comment' => <<'END_OF_FUNC',
1794 my($self,@p) = self_or_CGI(@_);
1795 return "<!-- @p -->";
1799 #### Method: checkbox
1800 # Create a checkbox that is not logically linked to any others.
1801 # The field value is "on" when the button is checked.
1803 # $name -> Name of the checkbox
1804 # $checked -> (optional) turned on by default if true
1805 # $value -> (optional) value of the checkbox, 'on' by default
1806 # $label -> (optional) a user-readable label printed next to the box.
1807 # Otherwise the checkbox name is used.
1809 # A string containing a <INPUT TYPE="checkbox"> field
1811 'checkbox' => <<'END_OF_FUNC',
1813 my($self,@p) = self_or_default(@_);
1815 my($name,$checked,$value,$label,$override,@other) =
1816 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1818 $value = defined $value ? $value : 'on';
1820 if (!$override && ($self->{'.fieldnames'}->{$name} ||
1821 defined $self->param($name))) {
1822 $checked = grep($_ eq $value,$self->param($name)) ? ' checked' : '';
1824 $checked = $checked ? qq/ checked/ : '';
1826 my($the_label) = defined $label ? $label : $name;
1827 $name = $self->escapeHTML($name);
1828 $value = $self->escapeHTML($value,1);
1829 $the_label = $self->escapeHTML($the_label);
1830 my($other) = @other ? " @other" : '';
1831 $self->register_parameter($name);
1832 return $XHTML ? qq{<input type="checkbox" name="$name" value="$value"$checked$other />$the_label}
1833 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
1838 #### Method: checkbox_group
1839 # Create a list of logically-linked checkboxes.
1841 # $name -> Common name for all the check boxes
1842 # $values -> A pointer to a regular array containing the
1843 # values for each checkbox in the group.
1844 # $defaults -> (optional)
1845 # 1. If a pointer to a regular array of checkbox values,
1846 # then this will be used to decide which
1847 # checkboxes to turn on by default.
1848 # 2. If a scalar, will be assumed to hold the
1849 # value of a single checkbox in the group to turn on.
1850 # $linebreak -> (optional) Set to true to place linebreaks
1851 # between the buttons.
1852 # $labels -> (optional)
1853 # A pointer to an associative array of labels to print next to each checkbox
1854 # in the form $label{'value'}="Long explanatory label".
1855 # Otherwise the provided values are used as the labels.
1857 # An ARRAY containing a series of <INPUT TYPE="checkbox"> fields
1859 'checkbox_group' => <<'END_OF_FUNC',
1860 sub checkbox_group {
1861 my($self,@p) = self_or_default(@_);
1863 my($name,$values,$defaults,$linebreak,$labels,$rows,$columns,
1864 $rowheaders,$colheaders,$override,$nolabels,@other) =
1865 rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
1866 LINEBREAK,LABELS,ROWS,[COLUMNS,COLS],
1867 ROWHEADERS,COLHEADERS,
1868 [OVERRIDE,FORCE],NOLABELS],@p);
1870 my($checked,$break,$result,$label);
1872 my(%checked) = $self->previous_or_default($name,$defaults,$override);
1875 $break = $XHTML ? "<br />" : "<br>";
1880 $name=$self->escapeHTML($name);
1882 # Create the elements
1883 my(@elements,@values);
1885 @values = $self->_set_values_and_labels($values,\$labels,$name);
1887 my($other) = @other ? " @other" : '';
1889 $checked = $checked{$_} ? qq/ checked/ : '';
1891 unless (defined($nolabels) && $nolabels) {
1893 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
1894 $label = $self->escapeHTML($label);
1896 $_ = $self->escapeHTML($_,1);
1897 push(@elements,$XHTML ? qq(<input type="checkbox" name="$name" value="$_"$checked$other />${label}${break})
1898 : qq/<input type="checkbox" name="$name" value="$_"$checked$other>${label}${break}/);
1900 $self->register_parameter($name);
1901 return wantarray ? @elements : join(' ',@elements)
1902 unless defined($columns) || defined($rows);
1903 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
1907 # Escape HTML -- used internally
1908 'escapeHTML' => <<'END_OF_FUNC',
1910 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
1911 return undef unless defined($toencode);
1912 return $toencode if ref($self) && $self->{'dontescape'};
1913 $toencode =~ s{&}{&}gso;
1914 $toencode =~ s{<}{<}gso;
1915 $toencode =~ s{>}{>}gso;
1916 $toencode =~ s{"}{"}gso;
1917 my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
1918 uc $self->{'.charset'} eq 'WINDOWS-1252';
1919 if ($latin) { # bug in some browsers
1920 $toencode =~ s{'}{'}gso;
1921 $toencode =~ s{\x8b}{‹}gso;
1922 $toencode =~ s{\x9b}{›}gso;
1923 if (defined $newlinestoo && $newlinestoo) {
1924 $toencode =~ s{\012}{ }gso;
1925 $toencode =~ s{\015}{ }gso;
1932 # unescape HTML -- used internally
1933 'unescapeHTML' => <<'END_OF_FUNC',
1935 my ($self,$string) = CGI::self_or_default(@_);
1936 return undef unless defined($string);
1937 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
1939 # thanks to Randal Schwartz for the correct solution to this one
1940 $string=~ s[&(.*?);]{
1946 /^#(\d+)$/ && $latin ? chr($1) :
1947 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
1954 # Internal procedure - don't use
1955 '_tableize' => <<'END_OF_FUNC',
1957 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
1958 $rowheaders = [] unless defined $rowheaders;
1959 $colheaders = [] unless defined $colheaders;
1962 if (defined($columns)) {
1963 $rows = int(0.99 + @elements/$columns) unless defined($rows);
1965 if (defined($rows)) {
1966 $columns = int(0.99 + @elements/$rows) unless defined($columns);
1969 # rearrange into a pretty table
1970 $result = "<table>";
1972 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
1973 $result .= "<tr>" if @{$colheaders};
1974 foreach (@{$colheaders}) {
1975 $result .= "<th>$_</th>";
1977 for ($row=0;$row<$rows;$row++) {
1979 $result .= "<th>$rowheaders->[$row]</th>" if @$rowheaders;
1980 for ($column=0;$column<$columns;$column++) {
1981 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
1982 if defined($elements[$column*$rows + $row]);
1986 $result .= "</table>";
1992 #### Method: radio_group
1993 # Create a list of logically-linked radio buttons.
1995 # $name -> Common name for all the buttons.
1996 # $values -> A pointer to a regular array containing the
1997 # values for each button in the group.
1998 # $default -> (optional) Value of the button to turn on by default. Pass '-'
1999 # to turn _nothing_ on.
2000 # $linebreak -> (optional) Set to true to place linebreaks
2001 # between the buttons.
2002 # $labels -> (optional)
2003 # A pointer to an associative array of labels to print next to each checkbox
2004 # in the form $label{'value'}="Long explanatory label".
2005 # Otherwise the provided values are used as the labels.
2007 # An ARRAY containing a series of <INPUT TYPE="radio"> fields
2009 'radio_group' => <<'END_OF_FUNC',
2011 my($self,@p) = self_or_default(@_);
2013 my($name,$values,$default,$linebreak,$labels,
2014 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
2015 rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,
2016 ROWS,[COLUMNS,COLS],
2017 ROWHEADERS,COLHEADERS,
2018 [OVERRIDE,FORCE],NOLABELS],@p);
2019 my($result,$checked);
2021 if (!$override && defined($self->param($name))) {
2022 $checked = $self->param($name);
2024 $checked = $default;
2026 my(@elements,@values);
2027 @values = $self->_set_values_and_labels($values,\$labels,$name);
2029 # If no check array is specified, check the first by default
2030 $checked = $values[0] unless defined($checked) && $checked ne '';
2031 $name=$self->escapeHTML($name);
2033 my($other) = @other ? " @other" : '';
2035 my($checkit) = $checked eq $_ ? qq/ checked/ : '';
2038 $break = $XHTML ? "<br />" : "<br>";
2044 unless (defined($nolabels) && $nolabels) {
2046 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2047 $label = $self->escapeHTML($label,1);
2049 $_=$self->escapeHTML($_);
2050 push(@elements,$XHTML ? qq(<input type="radio" name="$name" value="$_"$checkit$other />${label}${break})
2051 : qq/<input type="radio" name="$name" value="$_"$checkit$other>${label}${break}/);
2053 $self->register_parameter($name);
2054 return wantarray ? @elements : join(' ',@elements)
2055 unless defined($columns) || defined($rows);
2056 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2061 #### Method: popup_menu
2062 # Create a popup menu.
2064 # $name -> Name for all the menu
2065 # $values -> A pointer to a regular array containing the
2066 # text of each menu item.
2067 # $default -> (optional) Default item to display
2068 # $labels -> (optional)
2069 # A pointer to an associative array of labels to print next to each checkbox
2070 # in the form $label{'value'}="Long explanatory label".
2071 # Otherwise the provided values are used as the labels.
2073 # A string containing the definition of a popup menu.
2075 'popup_menu' => <<'END_OF_FUNC',
2077 my($self,@p) = self_or_default(@_);
2079 my($name,$values,$default,$labels,$override,@other) =
2080 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,[OVERRIDE,FORCE]],@p);
2081 my($result,$selected);
2083 if (!$override && defined($self->param($name))) {
2084 $selected = $self->param($name);
2086 $selected = $default;
2088 $name=$self->escapeHTML($name);
2089 my($other) = @other ? " @other" : '';
2092 @values = $self->_set_values_and_labels($values,\$labels,$name);
2094 $result = qq/<select name="$name"$other>\n/;
2096 my($selectit) = defined($selected) ? ($selected eq $_ ? qq/selected/ : '' ) : '';
2098 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2099 my($value) = $self->escapeHTML($_);
2100 $label=$self->escapeHTML($label,1);
2101 $result .= "<option $selectit value=\"$value\">$label</option>\n";
2104 $result .= "</select>";
2110 #### Method: scrolling_list
2111 # Create a scrolling list.
2113 # $name -> name for the list
2114 # $values -> A pointer to a regular array containing the
2115 # values for each option line in the list.
2116 # $defaults -> (optional)
2117 # 1. If a pointer to a regular array of options,
2118 # then this will be used to decide which
2119 # lines to turn on by default.
2120 # 2. Otherwise holds the value of the single line to turn on.
2121 # $size -> (optional) Size of the list.
2122 # $multiple -> (optional) If set, allow multiple selections.
2123 # $labels -> (optional)
2124 # A pointer to an associative array of labels to print next to each checkbox
2125 # in the form $label{'value'}="Long explanatory label".
2126 # Otherwise the provided values are used as the labels.
2128 # A string containing the definition of a scrolling list.
2130 'scrolling_list' => <<'END_OF_FUNC',
2131 sub scrolling_list {
2132 my($self,@p) = self_or_default(@_);
2133 my($name,$values,$defaults,$size,$multiple,$labels,$override,@other)
2134 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2135 SIZE,MULTIPLE,LABELS,[OVERRIDE,FORCE]],@p);
2137 my($result,@values);
2138 @values = $self->_set_values_and_labels($values,\$labels,$name);
2140 $size = $size || scalar(@values);
2142 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2143 my($is_multiple) = $multiple ? qq/ multiple/ : '';
2144 my($has_size) = $size ? qq/ size="$size"/: '';
2145 my($other) = @other ? " @other" : '';
2147 $name=$self->escapeHTML($name);
2148 $result = qq/<select name="$name"$has_size$is_multiple$other>\n/;
2150 my($selectit) = $selected{$_} ? qq/selected/ : '';
2152 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2153 $label=$self->escapeHTML($label);
2154 my($value)=$self->escapeHTML($_,1);
2155 $result .= "<option $selectit value=\"$value\">$label</option>\n";
2157 $result .= "</select>";
2158 $self->register_parameter($name);
2166 # $name -> Name of the hidden field
2167 # @default -> (optional) Initial values of field (may be an array)
2169 # $default->[initial values of field]
2171 # A string containing a <INPUT TYPE="hidden" NAME="name" VALUE="value">
2173 'hidden' => <<'END_OF_FUNC',
2175 my($self,@p) = self_or_default(@_);
2177 # this is the one place where we departed from our standard
2178 # calling scheme, so we have to special-case (darn)
2180 my($name,$default,$override,@other) =
2181 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2183 my $do_override = 0;
2184 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2185 @value = ref($default) ? @{$default} : $default;
2186 $do_override = $override;
2188 foreach ($default,$override,@other) {
2189 push(@value,$_) if defined($_);
2193 # use previous values if override is not set
2194 my @prev = $self->param($name);
2195 @value = @prev if !$do_override && @prev;
2197 $name=$self->escapeHTML($name);
2199 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2200 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" />)
2201 : qq(<input type="hidden" name="$name" value="$_">);
2203 return wantarray ? @result : join('',@result);
2208 #### Method: image_button
2210 # $name -> Name of the button
2211 # $src -> URL of the image source
2212 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2214 # A string containing a <INPUT TYPE="image" NAME="name" SRC="url" ALIGN="alignment">
2216 'image_button' => <<'END_OF_FUNC',
2218 my($self,@p) = self_or_default(@_);
2220 my($name,$src,$alignment,@other) =
2221 rearrange([NAME,SRC,ALIGN],@p);
2223 my($align) = $alignment ? " align=\U$alignment" : '';
2224 my($other) = @other ? " @other" : '';
2225 $name=$self->escapeHTML($name);
2226 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2227 : qq/<input type="image" name="$name" src="$src"$align$other>/;
2232 #### Method: self_url
2233 # Returns a URL containing the current script and all its
2234 # param/value pairs arranged as a query. You can use this
2235 # to create a link that, when selected, will reinvoke the
2236 # script with all its state information preserved.
2238 'self_url' => <<'END_OF_FUNC',
2240 my($self,@p) = self_or_default(@_);
2241 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2246 # This is provided as a synonym to self_url() for people unfortunate
2247 # enough to have incorporated it into their programs already!
2248 'state' => <<'END_OF_FUNC',
2256 # Like self_url, but doesn't return the query string part of
2259 'url' => <<'END_OF_FUNC',
2261 my($self,@p) = self_or_default(@_);
2262 my ($relative,$absolute,$full,$path_info,$query,$base) =
2263 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE'],@p);
2265 $full++ if $base || !($relative || $absolute);
2267 my $path = $self->path_info;
2268 my $script_name = $self->script_name;
2270 # If anybody knows why I ever wrote this please tell me!
2271 # if (exists($ENV{REQUEST_URI})) {
2273 # $script_name = $ENV{REQUEST_URI};
2274 # # strip query string
2275 # substr($script_name,$index) = '' if ($index = index($script_name,'?')) >= 0;
2277 # if (exists($ENV{PATH_INFO})) {
2278 # (my $encoded_path = $ENV{PATH_INFO}) =~ s!([^a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;;
2279 # substr($script_name,$index) = '' if ($index = rindex($script_name,$encoded_path)) >= 0;
2282 # $script_name = $self->script_name;
2286 my $protocol = $self->protocol();
2287 $url = "$protocol://";
2288 my $vh = http('host');
2292 $url .= server_name();
2293 my $port = $self->server_port;
2295 unless (lc($protocol) eq 'http' && $port == 80)
2296 || (lc($protocol) eq 'https' && $port == 443);
2298 return $url if $base;
2299 $url .= $script_name;
2300 } elsif ($relative) {
2301 ($url) = $script_name =~ m!([^/]+)$!;
2302 } elsif ($absolute) {
2303 $url = $script_name;
2306 $url .= $path if $path_info and defined $path;
2307 $url .= "?" . $self->query_string if $query and $self->query_string;
2308 $url = '' unless defined $url;
2309 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/uc sprintf("%%%02x",ord($1))/eg;
2316 # Set or read a cookie from the specified name.
2317 # Cookie can then be passed to header().
2318 # Usual rules apply to the stickiness of -value.
2320 # -name -> name for this cookie (optional)
2321 # -value -> value of this cookie (scalar, array or hash)
2322 # -path -> paths for which this cookie is valid (optional)
2323 # -domain -> internet domain in which this cookie is valid (optional)
2324 # -secure -> if true, cookie only passed through secure channel (optional)
2325 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2327 'cookie' => <<'END_OF_FUNC',
2329 my($self,@p) = self_or_default(@_);
2330 my($name,$value,$path,$domain,$secure,$expires) =
2331 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2333 require CGI::Cookie;
2335 # if no value is supplied, then we retrieve the
2336 # value of the cookie, if any. For efficiency, we cache the parsed
2337 # cookies in our state variables.
2338 unless ( defined($value) ) {
2339 $self->{'.cookies'} = CGI::Cookie->fetch
2340 unless $self->{'.cookies'};
2342 # If no name is supplied, then retrieve the names of all our cookies.
2343 return () unless $self->{'.cookies'};
2344 return keys %{$self->{'.cookies'}} unless $name;
2345 return () unless $self->{'.cookies'}->{$name};
2346 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2349 # If we get here, we're creating a new cookie
2350 return undef unless defined($name) && $name ne ''; # this is an error
2353 push(@param,'-name'=>$name);
2354 push(@param,'-value'=>$value);
2355 push(@param,'-domain'=>$domain) if $domain;
2356 push(@param,'-path'=>$path) if $path;
2357 push(@param,'-expires'=>$expires) if $expires;
2358 push(@param,'-secure'=>$secure) if $secure;
2360 return new CGI::Cookie(@param);
2364 'parse_keywordlist' => <<'END_OF_FUNC',
2365 sub parse_keywordlist {
2366 my($self,$tosplit) = @_;
2367 $tosplit = unescape($tosplit); # unescape the keywords
2368 $tosplit=~tr/+/ /; # pluses to spaces
2369 my(@keywords) = split(/\s+/,$tosplit);
2374 'param_fetch' => <<'END_OF_FUNC',
2376 my($self,@p) = self_or_default(@_);
2377 my($name) = rearrange([NAME],@p);
2378 unless (exists($self->{$name})) {
2379 $self->add_parameter($name);
2380 $self->{$name} = [];
2383 return $self->{$name};
2387 ###############################################
2388 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2389 ###############################################
2391 #### Method: path_info
2392 # Return the extra virtual path information provided
2393 # after the URL (if any)
2395 'path_info' => <<'END_OF_FUNC',
2397 my ($self,$info) = self_or_default(@_);
2398 if (defined($info)) {
2399 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2400 $self->{'.path_info'} = $info;
2401 } elsif (! defined($self->{'.path_info'}) ) {
2402 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2403 $ENV{'PATH_INFO'} : '';
2405 # hack to fix broken path info in IIS
2406 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2409 return $self->{'.path_info'};
2414 #### Method: request_method
2415 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2417 'request_method' => <<'END_OF_FUNC',
2418 sub request_method {
2419 return $ENV{'REQUEST_METHOD'};
2423 #### Method: content_type
2424 # Returns the content_type string
2426 'content_type' => <<'END_OF_FUNC',
2428 return $ENV{'CONTENT_TYPE'};
2432 #### Method: path_translated
2433 # Return the physical path information provided
2434 # by the URL (if any)
2436 'path_translated' => <<'END_OF_FUNC',
2437 sub path_translated {
2438 return $ENV{'PATH_TRANSLATED'};
2443 #### Method: query_string
2444 # Synthesize a query string from our current
2447 'query_string' => <<'END_OF_FUNC',
2449 my($self) = self_or_default(@_);
2450 my($param,$value,@pairs);
2451 foreach $param ($self->param) {
2452 my($eparam) = escape($param);
2453 foreach $value ($self->param($param)) {
2454 $value = escape($value);
2455 next unless defined $value;
2456 push(@pairs,"$eparam=$value");
2459 foreach (keys %{$self->{'.fieldnames'}}) {
2460 push(@pairs,".cgifields=".escape("$_"));
2462 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2468 # Without parameters, returns an array of the
2469 # MIME types the browser accepts.
2470 # With a single parameter equal to a MIME
2471 # type, will return undef if the browser won't
2472 # accept it, 1 if the browser accepts it but
2473 # doesn't give a preference, or a floating point
2474 # value between 0.0 and 1.0 if the browser
2475 # declares a quantitative score for it.
2476 # This handles MIME type globs correctly.
2478 'Accept' => <<'END_OF_FUNC',
2480 my($self,$search) = self_or_CGI(@_);
2481 my(%prefs,$type,$pref,$pat);
2483 my(@accept) = split(',',$self->http('accept'));
2486 ($pref) = /q=(\d\.\d+|\d+)/;
2487 ($type) = m#(\S+/[^;]+)#;
2489 $prefs{$type}=$pref || 1;
2492 return keys %prefs unless $search;
2494 # if a search type is provided, we may need to
2495 # perform a pattern matching operation.
2496 # The MIME types use a glob mechanism, which
2497 # is easily translated into a perl pattern match
2499 # First return the preference for directly supported
2501 return $prefs{$search} if $prefs{$search};
2503 # Didn't get it, so try pattern matching.
2504 foreach (keys %prefs) {
2505 next unless /\*/; # not a pattern match
2506 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2507 $pat =~ s/\*/.*/g; # turn it into a pattern
2508 return $prefs{$_} if $search=~/$pat/;
2514 #### Method: user_agent
2515 # If called with no parameters, returns the user agent.
2516 # If called with one parameter, does a pattern match (case
2517 # insensitive) on the user agent.
2519 'user_agent' => <<'END_OF_FUNC',
2521 my($self,$match)=self_or_CGI(@_);
2522 return $self->http('user_agent') unless $match;
2523 return $self->http('user_agent') =~ /$match/i;
2528 #### Method: raw_cookie
2529 # Returns the magic cookies for the session.
2530 # The cookies are not parsed or altered in any way, i.e.
2531 # cookies are returned exactly as given in the HTTP
2532 # headers. If a cookie name is given, only that cookie's
2533 # value is returned, otherwise the entire raw cookie
2536 'raw_cookie' => <<'END_OF_FUNC',
2538 my($self,$key) = self_or_CGI(@_);
2540 require CGI::Cookie;
2542 if (defined($key)) {
2543 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2544 unless $self->{'.raw_cookies'};
2546 return () unless $self->{'.raw_cookies'};
2547 return () unless $self->{'.raw_cookies'}->{$key};
2548 return $self->{'.raw_cookies'}->{$key};
2550 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2554 #### Method: virtual_host
2555 # Return the name of the virtual_host, which
2556 # is not always the same as the server
2558 'virtual_host' => <<'END_OF_FUNC',
2560 my $vh = http('host') || server_name();
2561 $vh =~ s/:\d+$//; # get rid of port number
2566 #### Method: remote_host
2567 # Return the name of the remote host, or its IP
2568 # address if unavailable. If this variable isn't
2569 # defined, it returns "localhost" for debugging
2572 'remote_host' => <<'END_OF_FUNC',
2574 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2580 #### Method: remote_addr
2581 # Return the IP addr of the remote host.
2583 'remote_addr' => <<'END_OF_FUNC',
2585 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2590 #### Method: script_name
2591 # Return the partial URL to this script for
2592 # self-referencing scripts. Also see
2593 # self_url(), which returns a URL with all state information
2596 'script_name' => <<'END_OF_FUNC',
2598 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2599 # These are for debugging
2600 return "/$0" unless $0=~/^\//;
2606 #### Method: referer
2607 # Return the HTTP_REFERER: useful for generating
2610 'referer' => <<'END_OF_FUNC',
2612 my($self) = self_or_CGI(@_);
2613 return $self->http('referer');
2618 #### Method: server_name
2619 # Return the name of the server
2621 'server_name' => <<'END_OF_FUNC',
2623 return $ENV{'SERVER_NAME'} || 'localhost';
2627 #### Method: server_software
2628 # Return the name of the server software
2630 'server_software' => <<'END_OF_FUNC',
2631 sub server_software {
2632 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2636 #### Method: server_port
2637 # Return the tcp/ip port the server is running on
2639 'server_port' => <<'END_OF_FUNC',
2641 return $ENV{'SERVER_PORT'} || 80; # for debugging
2645 #### Method: server_protocol
2646 # Return the protocol (usually HTTP/1.0)
2648 'server_protocol' => <<'END_OF_FUNC',
2649 sub server_protocol {
2650 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2655 # Return the value of an HTTP variable, or
2656 # the list of variables if none provided
2658 'http' => <<'END_OF_FUNC',
2660 my ($self,$parameter) = self_or_CGI(@_);
2661 return $ENV{$parameter} if $parameter=~/^HTTP/;
2662 $parameter =~ tr/-/_/;
2663 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2665 foreach (keys %ENV) {
2666 push(@p,$_) if /^HTTP/;
2673 # Return the value of HTTPS
2675 'https' => <<'END_OF_FUNC',
2678 my ($self,$parameter) = self_or_CGI(@_);
2679 return $ENV{HTTPS} unless $parameter;
2680 return $ENV{$parameter} if $parameter=~/^HTTPS/;
2681 $parameter =~ tr/-/_/;
2682 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2684 foreach (keys %ENV) {
2685 push(@p,$_) if /^HTTPS/;
2691 #### Method: protocol
2692 # Return the protocol (http or https currently)
2694 'protocol' => <<'END_OF_FUNC',
2698 return 'https' if uc($self->https()) eq 'ON';
2699 return 'https' if $self->server_port == 443;
2700 my $prot = $self->server_protocol;
2701 my($protocol,$version) = split('/',$prot);
2702 return "\L$protocol\E";
2706 #### Method: remote_ident
2707 # Return the identity of the remote user
2708 # (but only if his host is running identd)
2710 'remote_ident' => <<'END_OF_FUNC',
2712 return $ENV{'REMOTE_IDENT'};
2717 #### Method: auth_type
2718 # Return the type of use verification/authorization in use, if any.
2720 'auth_type' => <<'END_OF_FUNC',
2722 return $ENV{'AUTH_TYPE'};
2727 #### Method: remote_user
2728 # Return the authorization name used for user
2731 'remote_user' => <<'END_OF_FUNC',
2733 return $ENV{'REMOTE_USER'};
2738 #### Method: user_name
2739 # Try to return the remote user's name by hook or by
2742 'user_name' => <<'END_OF_FUNC',
2744 my ($self) = self_or_CGI(@_);
2745 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2749 #### Method: nosticky
2750 # Set or return the NOSTICKY global flag
2752 'nosticky' => <<'END_OF_FUNC',
2754 my ($self,$param) = self_or_CGI(@_);
2755 $CGI::NOSTICKY = $param if defined($param);
2756 return $CGI::NOSTICKY;
2761 # Set or return the NPH global flag
2763 'nph' => <<'END_OF_FUNC',
2765 my ($self,$param) = self_or_CGI(@_);
2766 $CGI::NPH = $param if defined($param);
2771 #### Method: private_tempfiles
2772 # Set or return the private_tempfiles global flag
2774 'private_tempfiles' => <<'END_OF_FUNC',
2775 sub private_tempfiles {
2776 my ($self,$param) = self_or_CGI(@_);
2777 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
2778 return $CGI::PRIVATE_TEMPFILES;
2782 #### Method: default_dtd
2783 # Set or return the default_dtd global
2785 'default_dtd' => <<'END_OF_FUNC',
2787 my ($self,$param,$param2) = self_or_CGI(@_);
2788 if (defined $param2 && defined $param) {
2789 $CGI::DEFAULT_DTD = [ $param, $param2 ];
2790 } elsif (defined $param) {
2791 $CGI::DEFAULT_DTD = $param;
2793 return $CGI::DEFAULT_DTD;
2797 # -------------- really private subroutines -----------------
2798 'previous_or_default' => <<'END_OF_FUNC',
2799 sub previous_or_default {
2800 my($self,$name,$defaults,$override) = @_;
2803 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2804 defined($self->param($name)) ) ) {
2805 grep($selected{$_}++,$self->param($name));
2806 } elsif (defined($defaults) && ref($defaults) &&
2807 (ref($defaults) eq 'ARRAY')) {
2808 grep($selected{$_}++,@{$defaults});
2810 $selected{$defaults}++ if defined($defaults);
2817 'register_parameter' => <<'END_OF_FUNC',
2818 sub register_parameter {
2819 my($self,$param) = @_;
2820 $self->{'.parametersToAdd'}->{$param}++;
2824 'get_fields' => <<'END_OF_FUNC',
2827 return $self->CGI::hidden('-name'=>'.cgifields',
2828 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
2833 'read_from_cmdline' => <<'END_OF_FUNC',
2834 sub read_from_cmdline {
2837 if ($DEBUG && @ARGV) {
2839 } elsif ($DEBUG > 1) {
2840 require "shellwords.pl";
2841 print STDERR "(offline mode: enter name=value pairs on standard input)\n";
2842 chomp(@lines = <STDIN>); # remove newlines
2843 $input = join(" ",@lines);
2844 @words = &shellwords($input);
2851 if ("@words"=~/=/) {
2852 $query_string = join('&',@words);
2854 $query_string = join('+',@words);
2856 return $query_string;
2861 # subroutine: read_multipart
2863 # Read multipart data and store it into our parameters.
2864 # An interesting feature is that if any of the parts is a file, we
2865 # create a temporary file and open up a filehandle on it so that the
2866 # caller can read from it if necessary.
2868 'read_multipart' => <<'END_OF_FUNC',
2869 sub read_multipart {
2870 my($self,$boundary,$length,$filehandle) = @_;
2871 my($buffer) = $self->new_MultipartBuffer($boundary,$length,$filehandle);
2872 return unless $buffer;
2875 while (!$buffer->eof) {
2876 %header = $buffer->readHeader;
2879 $self->cgi_error("400 Bad request (malformed multipart POST)");
2883 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
2885 # Bug: Netscape doesn't escape quotation marks in file names!!!
2886 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\"]*)"?/;
2888 # add this parameter to our list
2889 $self->add_parameter($param);
2891 # If no filename specified, then just read the data and assign it
2892 # to our parameter list.
2893 if ( !defined($filename) || $filename eq '' ) {
2894 my($value) = $buffer->readBody;
2895 push(@{$self->{$param}},$value);
2899 my ($tmpfile,$tmp,$filehandle);
2901 # If we get here, then we are dealing with a potentially large
2902 # uploaded form. Save the data to a temporary file, then open
2903 # the file for reading.
2905 # skip the file if uploads disabled
2906 if ($DISABLE_UPLOADS) {
2907 while (defined($data = $buffer->read)) { }
2911 # choose a relatively unpredictable tmpfile sequence number
2912 my $seqno = unpack("%16C*",join('',localtime,values %ENV));
2913 for (my $cnt=10;$cnt>0;$cnt--) {
2914 next unless $tmpfile = new TempFile($seqno);
2915 $tmp = $tmpfile->as_string;
2916 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
2917 $seqno += int rand(100);
2919 die "CGI open of tmpfile: $!\n" unless defined $filehandle;
2920 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2924 while (defined($data = $buffer->read)) {
2925 print $filehandle $data;
2928 # back up to beginning of file
2929 seek($filehandle,0,0);
2930 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
2932 # Save some information about the uploaded file where we can get
2934 $self->{'.tmpfiles'}->{fileno($filehandle)}= {
2938 push(@{$self->{$param}},$filehandle);
2944 'upload' =><<'END_OF_FUNC',
2946 my($self,$param_name) = self_or_default(@_);
2947 my @param = grep(ref && fileno($_), $self->param($param_name));
2948 return unless @param;
2949 return wantarray ? @param : $param[0];
2953 'tmpFileName' => <<'END_OF_FUNC',
2955 my($self,$filename) = self_or_default(@_);
2956 return $self->{'.tmpfiles'}->{fileno($filename)}->{name} ?
2957 $self->{'.tmpfiles'}->{fileno($filename)}->{name}->as_string
2962 'uploadInfo' => <<'END_OF_FUNC',
2964 my($self,$filename) = self_or_default(@_);
2965 return $self->{'.tmpfiles'}->{fileno($filename)}->{info};
2969 # internal routine, don't use
2970 '_set_values_and_labels' => <<'END_OF_FUNC',
2971 sub _set_values_and_labels {
2974 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
2975 return $self->param($n) if !defined($v);
2976 return $v if !ref($v);
2977 return ref($v) eq 'HASH' ? keys %$v : @$v;
2981 '_compile_all' => <<'END_OF_FUNC',
2984 next if defined(&$_);
2985 $AUTOLOAD = "CGI::$_";
2995 #########################################################
2996 # Globals and stubs for other packages that we use.
2997 #########################################################
2999 ################### Fh -- lightweight filehandle ###############
3008 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3010 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3011 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3013 'asString' => <<'END_OF_FUNC',
3016 # get rid of package name
3017 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
3018 $i =~ s/%(..)/ chr(hex($1)) /eg;
3021 # This was an extremely clever patch that allowed "use strict refs".
3022 # Unfortunately it relied on another bug that caused leaky file descriptors.
3023 # The underlying bug has been fixed, so this no longer works. However
3024 # "strict refs" still works for some reason.
3026 # return ${*{$self}{SCALAR}};
3031 'compare' => <<'END_OF_FUNC',
3035 return "$self" cmp $value;
3039 'new' => <<'END_OF_FUNC',
3041 my($pack,$name,$file,$delete) = @_;
3042 require Fcntl unless defined &Fcntl::O_RDWR;
3043 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3044 my $fv = ++$FH . $safename;
3045 my $ref = \*{"Fh::$fv"};
3046 sysopen($ref,$file,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3047 unlink($file) if $delete;
3048 CORE::delete $Fh::{$fv};
3049 return bless $ref,$pack;
3053 'DESTROY' => <<'END_OF_FUNC',
3063 ######################## MultipartBuffer ####################
3064 package MultipartBuffer;
3066 # how many bytes to read at a time. We use
3067 # a 4K buffer by default.
3068 $INITIAL_FILLUNIT = 1024 * 4;
3069 $TIMEOUT = 240*60; # 4 hour timeout for big files
3070 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3073 #reuse the autoload function
3074 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3076 # avoid autoloader warnings
3079 ###############################################################################
3080 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3081 ###############################################################################
3082 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3083 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3086 'new' => <<'END_OF_FUNC',
3088 my($package,$interface,$boundary,$length,$filehandle) = @_;
3089 $FILLUNIT = $INITIAL_FILLUNIT;
3092 my($package) = caller;
3093 # force into caller's package if necessary
3094 $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
3096 $IN = "main::STDIN" unless $IN;
3098 $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
3100 # If the user types garbage into the file upload field,
3101 # then Netscape passes NOTHING to the server (not good).
3102 # We may hang on this read in that case. So we implement
3103 # a read timeout. If nothing is ready to read
3104 # by then, we return.
3106 # Netscape seems to be a little bit unreliable
3107 # about providing boundary strings.
3108 my $boundary_read = 0;
3111 # Under the MIME spec, the boundary consists of the
3112 # characters "--" PLUS the Boundary string
3114 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3115 # the two extra hyphens. We do a special case here on the user-agent!!!!
3116 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac|DreamPassport');
3118 } else { # otherwise we find it ourselves
3120 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3121 $boundary = <$IN>; # BUG: This won't work correctly under mod_perl
3122 $length -= length($boundary);
3123 chomp($boundary); # remove the CRLF
3124 $/ = $old; # restore old line separator
3128 my $self = {LENGTH=>$length,
3129 BOUNDARY=>$boundary,
3131 INTERFACE=>$interface,
3135 $FILLUNIT = length($boundary)
3136 if length($boundary) > $FILLUNIT;
3138 my $retval = bless $self,ref $package || $package;
3140 # Read the preamble and the topmost (boundary) line plus the CRLF.
3141 unless ($boundary_read) {
3142 while ($self->read(0)) { }
3144 die "Malformed multipart POST\n" if $self->eof;
3150 'readHeader' => <<'END_OF_FUNC',
3157 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
3160 $self->fillBuffer($FILLUNIT);
3161 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3162 $ok++ if $self->{BUFFER} eq '';
3163 $bad++ if !$ok && $self->{LENGTH} <= 0;
3164 # this was a bad idea
3165 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3166 } until $ok || $bad;
3169 my($header) = substr($self->{BUFFER},0,$end+2);
3170 substr($self->{BUFFER},0,$end+4) = '';
3174 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3175 # (Folding Long Header Fields), 3.4.3 (Comments)
3176 # and 3.4.5 (Quoted-Strings).
3178 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3179 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3180 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3181 my ($field_name,$field_value) = ($1,$2); # avoid taintedness
3182 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3183 $return{$field_name}=$field_value;
3189 # This reads and returns the body as a single scalar value.
3190 'readBody' => <<'END_OF_FUNC',
3195 while (defined($data = $self->read)) {
3196 $returnval .= $data;
3202 # This will read $bytes or until the boundary is hit, whichever happens
3203 # first. After the boundary is hit, we return undef. The next read will
3204 # skip over the boundary and begin reading again;
3205 'read' => <<'END_OF_FUNC',
3207 my($self,$bytes) = @_;
3209 # default number of bytes to read
3210 $bytes = $bytes || $FILLUNIT;
3212 # Fill up our internal buffer in such a way that the boundary
3213 # is never split between reads.
3214 $self->fillBuffer($bytes);
3216 # Find the boundary in the buffer (it may not be there).
3217 my $start = index($self->{BUFFER},$self->{BOUNDARY});
3218 # protect against malformed multipart POST operations
3219 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3221 # If the boundary begins the data, then skip past it
3225 # clear us out completely if we've hit the last boundary.
3226 if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
3232 # just remove the boundary.
3233 substr($self->{BUFFER},0,length($self->{BOUNDARY}))='';
3234 $self->{BUFFER} =~ s/^\012\015?//;
3239 if ($start > 0) { # read up to the boundary
3240 $bytesToReturn = $start > $bytes ? $bytes : $start;
3241 } else { # read the requested number of bytes
3242 # leave enough bytes in the buffer to allow us to read
3243 # the boundary. Thanks to Kevin Hendrick for finding
3245 $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
3248 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3249 substr($self->{BUFFER},0,$bytesToReturn)='';
3251 # If we hit the boundary, remove the CRLF from the end.
3252 return ($start > 0) ? substr($returnval,0,-2) : $returnval;
3257 # This fills up our internal buffer in such a way that the
3258 # boundary is never split between reads
3259 'fillBuffer' => <<'END_OF_FUNC',
3261 my($self,$bytes) = @_;
3262 return unless $self->{LENGTH};
3264 my($boundaryLength) = length($self->{BOUNDARY});
3265 my($bufferLength) = length($self->{BUFFER});
3266 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3267 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3269 # Try to read some data. We may hang here if the browser is screwed up.
3270 my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
3274 $self->{BUFFER} = '' unless defined $self->{BUFFER};
3276 # An apparent bug in the Apache server causes the read()
3277 # to return zero bytes repeatedly without blocking if the
3278 # remote user aborts during a file transfer. I don't know how
3279 # they manage this, but the workaround is to abort if we get
3280 # more than SPIN_LOOP_MAX consecutive zero reads.
3281 if ($bytesRead == 0) {
3282 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3283 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3285 $self->{ZERO_LOOP_COUNTER}=0;
3288 $self->{LENGTH} -= $bytesRead;
3293 # Return true when we've finished reading
3294 'eof' => <<'END_OF_FUNC'
3297 return 1 if (length($self->{BUFFER}) == 0)
3298 && ($self->{LENGTH} <= 0);
3306 ####################################################################################
3307 ################################## TEMPORARY FILES #################################
3308 ####################################################################################
3312 $MAC = $CGI::OS eq 'MACINTOSH';
3313 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3314 unless ($TMPDIRECTORY) {
3315 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3316 "C:${SL}temp","${SL}tmp","${SL}temp",
3317 "${vol}${SL}Temporary Items",
3318 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3319 "C:${SL}system${SL}temp");
3320 unshift(@TEMP,$ENV{'TMPDIR'}) if exists $ENV{'TMPDIR'};
3322 # this feature was supposed to provide per-user tmpfiles, but
3323 # it is problematic.
3324 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3325 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3326 # : can generate a 'getpwuid() not implemented' exception, even though
3327 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3328 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3329 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3332 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3336 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3339 # cute feature, but overload implementation broke it
3340 # %OVERLOAD = ('""'=>'as_string');
3341 *TempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3343 ###############################################################################
3344 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3345 ###############################################################################
3346 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3347 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3350 'new' => <<'END_OF_FUNC',
3352 my($package,$sequence) = @_;
3354 for (my $i = 0; $i < $MAXTRIES; $i++) {
3355 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3357 # untaint the darn thing
3358 return unless $filename =~ m!^([a-zA-Z0-9_ '":/.\$\\-]+)$!;
3360 return bless \$filename;
3364 'DESTROY' => <<'END_OF_FUNC',
3367 unlink $$self; # get rid of the file
3371 'as_string' => <<'END_OF_FUNC'
3383 # We get a whole bunch of warnings about "possibly uninitialized variables"
3384 # when running with the -w switch. Touch them all once to get rid of the
3385 # warnings. This is ugly and I hate it.
3390 $MultipartBuffer::SPIN_LOOP_MAX;
3391 $MultipartBuffer::CRLF;
3392 $MultipartBuffer::TIMEOUT;
3393 $MultipartBuffer::INITIAL_FILLUNIT;
3404 CGI - Simple Common Gateway Interface Class
3408 # CGI script that creates a fill-out form
3409 # and echoes back its values.
3411 use CGI qw/:standard/;
3413 start_html('A Simple Example'),
3414 h1('A Simple Example'),
3416 "What's your name? ",textfield('name'),p,
3417 "What's the combination?", p,
3418 checkbox_group(-name=>'words',
3419 -values=>['eenie','meenie','minie','moe'],
3420 -defaults=>['eenie','minie']), p,
3421 "What's your favorite color? ",
3422 popup_menu(-name=>'color',
3423 -values=>['red','green','blue','chartreuse']),p,
3429 print "Your name is",em(param('name')),p,
3430 "The keywords are: ",em(join(", ",param('words'))),p,
3431 "Your favorite color is ",em(param('color')),
3437 This perl library uses perl5 objects to make it easy to create Web
3438 fill-out forms and parse their contents. This package defines CGI
3439 objects, entities that contain the values of the current query string
3440 and other state variables. Using a CGI object's methods, you can
3441 examine keywords and parameters passed to your script, and create
3442 forms whose initial values are taken from the current query (thereby
3443 preserving state information). The module provides shortcut functions
3444 that produce boilerplate HTML, reducing typing and coding errors. It
3445 also provides functionality for some of the more advanced features of
3446 CGI scripting, including support for file uploads, cookies, cascading
3447 style sheets, server push, and frames.
3449 CGI.pm also provides a simple function-oriented programming style for
3450 those who don't need its object-oriented features.
3452 The current version of CGI.pm is available at
3454 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3455 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3459 =head2 PROGRAMMING STYLE
3461 There are two styles of programming with CGI.pm, an object-oriented
3462 style and a function-oriented style. In the object-oriented style you
3463 create one or more CGI objects and then use object methods to create
3464 the various elements of the page. Each CGI object starts out with the
3465 list of named parameters that were passed to your CGI script by the
3466 server. You can modify the objects, save them to a file or database
3467 and recreate them. Because each object corresponds to the "state" of
3468 the CGI script, and because each object's parameter list is
3469 independent of the others, this allows you to save the state of the
3470 script and restore it later.
3472 For example, using the object oriented style, here is how you create
3473 a simple "Hello World" HTML page:
3475 #!/usr/local/bin/perl -w
3476 use CGI; # load CGI routines
3477 $q = new CGI; # create new CGI object
3478 print $q->header, # create the HTTP header
3479 $q->start_html('hello world'), # start the HTML
3480 $q->h1('hello world'), # level 1 header
3481 $q->end_html; # end the HTML
3483 In the function-oriented style, there is one default CGI object that
3484 you rarely deal with directly. Instead you just call functions to
3485 retrieve CGI parameters, create HTML tags, manage cookies, and so
3486 on. This provides you with a cleaner programming interface, but
3487 limits you to using one CGI object at a time. The following example
3488 prints the same page, but uses the function-oriented interface.
3489 The main differences are that we now need to import a set of functions
3490 into our name space (usually the "standard" functions), and we don't
3491 need to create the CGI object.
3493 #!/usr/local/bin/perl
3494 use CGI qw/:standard/; # load standard CGI routines
3495 print header, # create the HTTP header
3496 start_html('hello world'), # start the HTML
3497 h1('hello world'), # level 1 header
3498 end_html; # end the HTML
3500 The examples in this document mainly use the object-oriented style.
3501 See HOW TO IMPORT FUNCTIONS for important information on
3502 function-oriented programming in CGI.pm
3504 =head2 CALLING CGI.PM ROUTINES
3506 Most CGI.pm routines accept several arguments, sometimes as many as 20
3507 optional ones! To simplify this interface, all routines use a named
3508 argument calling style that looks like this:
3510 print $q->header(-type=>'image/gif',-expires=>'+3d');
3512 Each argument name is preceded by a dash. Neither case nor order
3513 matters in the argument list. -type, -Type, and -TYPE are all
3514 acceptable. In fact, only the first argument needs to begin with a
3515 dash. If a dash is present in the first argument, CGI.pm assumes
3516 dashes for the subsequent ones.
3518 Several routines are commonly called with just one argument. In the
3519 case of these routines you can provide the single argument without an
3520 argument name. header() happens to be one of these routines. In this
3521 case, the single argument is the document type.
3523 print $q->header('text/html');
3525 Other such routines are documented below.
3527 Sometimes named arguments expect a scalar, sometimes a reference to an
3528 array, and sometimes a reference to a hash. Often, you can pass any
3529 type of argument and the routine will do whatever is most appropriate.
3530 For example, the param() routine is used to set a CGI parameter to a
3531 single or a multi-valued value. The two cases are shown below:
3533 $q->param(-name=>'veggie',-value=>'tomato');
3534 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
3536 A large number of routines in CGI.pm actually aren't specifically
3537 defined in the module, but are generated automatically as needed.
3538 These are the "HTML shortcuts," routines that generate HTML tags for
3539 use in dynamically-generated pages. HTML tags have both attributes
3540 (the attribute="value" pairs within the tag itself) and contents (the
3541 part between the opening and closing pairs.) To distinguish between
3542 attributes and contents, CGI.pm uses the convention of passing HTML
3543 attributes as a hash reference as the first argument, and the
3544 contents, if any, as any subsequent arguments. It works out like
3550 h1('some','contents'); <H1>some contents</H1>
3551 h1({-align=>left}); <H1 ALIGN="LEFT">
3552 h1({-align=>left},'contents'); <H1 ALIGN="LEFT">contents</H1>
3554 HTML tags are described in more detail later.
3556 Many newcomers to CGI.pm are puzzled by the difference between the
3557 calling conventions for the HTML shortcuts, which require curly braces
3558 around the HTML tag attributes, and the calling conventions for other
3559 routines, which manage to generate attributes without the curly
3560 brackets. Don't be confused. As a convenience the curly braces are
3561 optional in all but the HTML shortcuts. If you like, you can use
3562 curly braces when calling any routine that takes named arguments. For
3565 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3567 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3568 names conflict with built-in Perl functions. The most frequent of
3569 these is the -values argument, used to create multi-valued menus,
3570 radio button clusters and the like. To get around this warning, you
3571 have several choices:
3577 Use another name for the argument, if one is available.
3578 For example, -value is an alias for -values.
3582 Change the capitalization, e.g. -Values
3586 Put quotes around the argument name, e.g. '-values'
3590 Many routines will do something useful with a named argument that it
3591 doesn't recognize. For example, you can produce non-standard HTTP
3592 header fields by providing them as named arguments:
3594 print $q->header(-type => 'text/html',
3595 -cost => 'Three smackers',
3596 -annoyance_level => 'high',
3597 -complaints_to => 'bit bucket');
3599 This will produce the following nonstandard HTTP header:
3602 Cost: Three smackers
3603 Annoyance-level: high
3604 Complaints-to: bit bucket
3605 Content-type: text/html
3607 Notice the way that underscores are translated automatically into
3608 hyphens. HTML-generating routines perform a different type of
3611 This feature allows you to keep up with the rapidly changing HTTP and
3614 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
3618 This will parse the input (from both POST and GET methods) and store
3619 it into a perl5 object called $query.
3621 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
3623 $query = new CGI(INPUTFILE);
3625 If you provide a file handle to the new() method, it will read
3626 parameters from the file (or STDIN, or whatever). The file can be in
3627 any of the forms describing below under debugging (i.e. a series of
3628 newline delimited TAG=VALUE pairs will work). Conveniently, this type
3629 of file is created by the save() method (see below). Multiple records
3630 can be saved and restored.
3632 Perl purists will be pleased to know that this syntax accepts
3633 references to file handles, or even references to filehandle globs,
3634 which is the "official" way to pass a filehandle:
3636 $query = new CGI(\*STDIN);
3638 You can also initialize the CGI object with a FileHandle or IO::File
3641 If you are using the function-oriented interface and want to
3642 initialize CGI state from a file handle, the way to do this is with
3643 B<restore_parameters()>. This will (re)initialize the
3644 default CGI object from the indicated file handle.
3646 open (IN,"test.in") || die;
3647 restore_parameters(IN);
3650 You can also initialize the query object from an associative array
3653 $query = new CGI( {'dinosaur'=>'barney',
3654 'song'=>'I love you',
3655 'friends'=>[qw/Jessica George Nancy/]}
3658 or from a properly formatted, URL-escaped query string:
3660 $query = new CGI('dinosaur=barney&color=purple');
3662 or from a previously existing CGI object (currently this clones the
3663 parameter list, but none of the other object-specific fields, such as
3666 $old_query = new CGI;
3667 $new_query = new CGI($old_query);
3669 To create an empty query, initialize it from an empty string or hash:
3671 $empty_query = new CGI("");
3675 $empty_query = new CGI({});
3677 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
3679 @keywords = $query->keywords
3681 If the script was invoked as the result of an <ISINDEX> search, the
3682 parsed keywords can be obtained as an array using the keywords() method.
3684 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
3686 @names = $query->param
3688 If the script was invoked with a parameter list
3689 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
3690 will return the parameter names as a list. If the script was invoked
3691 as an <ISINDEX> script and contains a string without ampersands
3692 (e.g. "value1+value2+value3") , there will be a single parameter named
3693 "keywords" containing the "+"-delimited keywords.
3695 NOTE: As of version 1.5, the array of parameter names returned will
3696 be in the same order as they were submitted by the browser.
3697 Usually this order is the same as the order in which the
3698 parameters are defined in the form (however, this isn't part
3699 of the spec, and so isn't guaranteed).
3701 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
3703 @values = $query->param('foo');
3707 $value = $query->param('foo');
3709 Pass the param() method a single argument to fetch the value of the
3710 named parameter. If the parameter is multivalued (e.g. from multiple
3711 selections in a scrolling list), you can ask to receive an array. Otherwise
3712 the method will return a single value.
3714 If a value is not given in the query string, as in the queries
3715 "name1=&name2=" or "name1&name2", it will be returned as an empty
3716 string. This feature is new in 2.63.
3718 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
3720 $query->param('foo','an','array','of','values');
3722 This sets the value for the named parameter 'foo' to an array of
3723 values. This is one way to change the value of a field AFTER
3724 the script has been invoked once before. (Another way is with
3725 the -override parameter accepted by all methods that generate
3728 param() also recognizes a named parameter style of calling described
3729 in more detail later:
3731 $query->param(-name=>'foo',-values=>['an','array','of','values']);
3735 $query->param(-name=>'foo',-value=>'the value');
3737 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
3739 $query->append(-name=>'foo',-values=>['yet','more','values']);
3741 This adds a value or list of values to the named parameter. The
3742 values are appended to the end of the parameter if it already exists.
3743 Otherwise the parameter is created. Note that this method only
3744 recognizes the named argument calling syntax.
3746 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
3748 $query->import_names('R');
3750 This creates a series of variables in the 'R' namespace. For example,
3751 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
3752 If no namespace is given, this method will assume 'Q'.
3753 WARNING: don't import anything into 'main'; this is a major security
3756 In older versions, this method was called B<import()>. As of version 2.20,
3757 this name has been removed completely to avoid conflict with the built-in
3758 Perl module B<import> operator.
3760 =head2 DELETING A PARAMETER COMPLETELY:
3762 $query->delete('foo');
3764 This completely clears a parameter. It sometimes useful for
3765 resetting parameters that you don't want passed down between
3768 If you are using the function call interface, use "Delete()" instead
3769 to avoid conflicts with Perl's built-in delete operator.
3771 =head2 DELETING ALL PARAMETERS:
3773 $query->delete_all();
3775 This clears the CGI object completely. It might be useful to ensure
3776 that all the defaults are taken when you create a fill-out form.
3778 Use Delete_all() instead if you are using the function call interface.
3780 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
3782 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
3783 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
3785 If you need access to the parameter list in a way that isn't covered
3786 by the methods above, you can obtain a direct reference to it by
3787 calling the B<param_fetch()> method with the name of the . This
3788 will return an array reference to the named parameters, which you then
3789 can manipulate in any way you like.
3791 You can also use a named argument style using the B<-name> argument.
3793 =head2 FETCHING THE PARAMETER LIST AS A HASH:
3796 print $params->{'address'};
3797 @foo = split("\0",$params->{'foo'});
3803 Many people want to fetch the entire parameter list as a hash in which
3804 the keys are the names of the CGI parameters, and the values are the
3805 parameters' values. The Vars() method does this. Called in a scalar
3806 context, it returns the parameter list as a tied hash reference.
3807 Changing a key changes the value of the parameter in the underlying
3808 CGI parameter list. Called in a list context, it returns the
3809 parameter list as an ordinary hash. This allows you to read the
3810 contents of the parameter list, but not to change it.
3812 When using this, the thing you must watch out for are multivalued CGI
3813 parameters. Because a hash cannot distinguish between scalar and
3814 list context, multivalued parameters will be returned as a packed
3815 string, separated by the "\0" (null) character. You must split this
3816 packed string in order to get at the individual values. This is the
3817 convention introduced long ago by Steve Brenner in his cgi-lib.pl
3818 module for Perl version 4.
3820 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
3821 function calls (also see the section on CGI-LIB compatibility).
3823 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
3825 $query->save(FILEHANDLE)
3827 This will write the current state of the form to the provided
3828 filehandle. You can read it back in by providing a filehandle
3829 to the new() method. Note that the filehandle can be a file, a pipe,
3832 The format of the saved file is:
3840 Both name and value are URL escaped. Multi-valued CGI parameters are
3841 represented as repeated names. A session record is delimited by a
3842 single = symbol. You can write out multiple records and read them
3843 back in with several calls to B<new>. You can do this across several
3844 sessions by opening the file in append mode, allowing you to create
3845 primitive guest books, or to keep a history of users' queries. Here's
3846 a short example of creating multiple session records:
3850 open (OUT,">>test.out") || die;
3852 foreach (0..$records) {
3854 $q->param(-name=>'counter',-value=>$_);
3859 # reopen for reading
3860 open (IN,"test.out") || die;
3862 my $q = new CGI(IN);
3863 print $q->param('counter'),"\n";
3866 The file format used for save/restore is identical to that used by the
3867 Whitehead Genome Center's data exchange format "Boulderio", and can be
3868 manipulated and even databased using Boulderio utilities. See
3870 http://stein.cshl.org/boulder/
3872 for further details.
3874 If you wish to use this method from the function-oriented (non-OO)
3875 interface, the exported name for this method is B<save_parameters()>.
3877 =head2 RETRIEVING CGI ERRORS
3879 Errors can occur while processing user input, particularly when
3880 processing uploaded files. When these errors occur, CGI will stop
3881 processing and return an empty parameter list. You can test for
3882 the existence and nature of errors using the I<cgi_error()> function.
3883 The error messages are formatted as HTTP status codes. You can either
3884 incorporate the error text into an HTML page, or use it as the value
3887 my $error = $q->cgi_error;
3889 print $q->header(-status=>$error),
3890 $q->start_html('Problems'),
3891 $q->h2('Request not processed'),
3896 When using the function-oriented interface (see the next section),
3897 errors may only occur the first time you call I<param()>. Be ready
3900 =head2 USING THE FUNCTION-ORIENTED INTERFACE
3902 To use the function-oriented interface, you must specify which CGI.pm
3903 routines or sets of routines to import into your script's namespace.
3904 There is a small overhead associated with this importation, but it
3907 use CGI <list of methods>;
3909 The listed methods will be imported into the current package; you can
3910 call them directly without creating a CGI object first. This example
3911 shows how to import the B<param()> and B<header()>
3912 methods, and then use them directly:
3914 use CGI 'param','header';
3915 print header('text/plain');
3916 $zipcode = param('zipcode');
3918 More frequently, you'll import common sets of functions by referring
3919 to the groups by name. All function sets are preceded with a ":"
3920 character as in ":html3" (for tags defined in the HTML 3 standard).
3922 Here is a list of the function sets you can import:
3928 Import all CGI-handling methods, such as B<param()>, B<path_info()>
3933 Import all fill-out form generating methods, such as B<textfield()>.
3937 Import all methods that generate HTML 2.0 standard elements.
3941 Import all methods that generate HTML 3.0 proposed elements (such as
3942 <table>, <super> and <sub>).
3946 Import all methods that generate Netscape-specific HTML extensions.
3950 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
3955 Import "standard" features, 'html2', 'html3', 'form' and 'cgi'.
3959 Import all the available methods. For the full list, see the CGI.pm
3960 code, where the variable %EXPORT_TAGS is defined.
3964 If you import a function name that is not part of CGI.pm, the module
3965 will treat it as a new HTML tag and generate the appropriate
3966 subroutine. You can then use it like any other HTML tag. This is to
3967 provide for the rapidly-evolving HTML "standard." For example, say
3968 Microsoft comes out with a new tag called <GRADIENT> (which causes the
3969 user's desktop to be flooded with a rotating gradient fill until his
3970 machine reboots). You don't need to wait for a new version of CGI.pm
3971 to start using it immediately:
3973 use CGI qw/:standard :html3 gradient/;
3974 print gradient({-start=>'red',-end=>'blue'});
3976 Note that in the interests of execution speed CGI.pm does B<not> use
3977 the standard L<Exporter> syntax for specifying load symbols. This may
3978 change in the future.
3980 If you import any of the state-maintaining CGI or form-generating
3981 methods, a default CGI object will be created and initialized
3982 automatically the first time you use any of the methods that require
3983 one to be present. This includes B<param()>, B<textfield()>,
3984 B<submit()> and the like. (If you need direct access to the CGI
3985 object, you can find it in the global variable B<$CGI::Q>). By
3986 importing CGI.pm methods, you can create visually elegant scripts:
3988 use CGI qw/:standard/;
3991 start_html('Simple Script'),
3992 h1('Simple Script'),
3994 "What's your name? ",textfield('name'),p,
3995 "What's the combination?",
3996 checkbox_group(-name=>'words',
3997 -values=>['eenie','meenie','minie','moe'],
3998 -defaults=>['eenie','moe']),p,
3999 "What's your favorite color?",
4000 popup_menu(-name=>'color',
4001 -values=>['red','green','blue','chartreuse']),p,
4008 "Your name is ",em(param('name')),p,
4009 "The keywords are: ",em(join(", ",param('words'))),p,
4010 "Your favorite color is ",em(param('color')),".\n";
4016 In addition to the function sets, there are a number of pragmas that
4017 you can import. Pragmas, which are always preceded by a hyphen,
4018 change the way that CGI.pm functions in various ways. Pragmas,
4019 function sets, and individual functions can all be imported in the
4020 same use() line. For example, the following use statement imports the
4021 standard set of functions and enables debugging mode (pragma
4024 use CGI qw/:standard -debug/;
4026 The current list of pragmas is as follows:
4032 When you I<use CGI -any>, then any method that the query object
4033 doesn't recognize will be interpreted as a new HTML tag. This allows
4034 you to support the next I<ad hoc> Netscape or Microsoft HTML
4035 extension. This lets you go wild with new and unsupported tags:
4039 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4041 Since using <cite>any</cite> causes any mistyped method name
4042 to be interpreted as an HTML tag, use it with care or not at
4047 This causes the indicated autoloaded methods to be compiled up front,
4048 rather than deferred to later. This is useful for scripts that run
4049 for an extended period of time under FastCGI or mod_perl, and for
4050 those destined to be crunched by Malcom Beattie's Perl compiler. Use
4051 it in conjunction with the methods or method families you plan to use.
4053 use CGI qw(-compile :standard :html3);
4057 use CGI qw(-compile :all);
4059 Note that using the -compile pragma in this way will always have
4060 the effect of importing the compiled functions into the current
4061 namespace. If you want to compile without importing use the
4062 compile() method instead (see below).
4066 This makes CGI.pm not generating the hidden fields .submit
4067 and .cgifields. It is very useful if you don't want to
4068 have the hidden fields appear in the querystring in a GET method.
4069 For example, a search script generated this way will have
4070 a very nice url with search parameters for bookmarking.
4072 =item -no_undef_params
4074 This keeps CGI.pm from including undef params in the parameter list.
4078 By default, CGI.pm versions 2.69 and higher emit XHTML
4079 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4080 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4085 This makes CGI.pm produce a header appropriate for an NPH (no
4086 parsed header) script. You may need to do other things as well
4087 to tell the server that the script is NPH. See the discussion
4088 of NPH scripts below.
4090 =item -newstyle_urls
4092 Separate the name=value pairs in CGI parameter query strings with
4093 semicolons rather than ampersands. For example:
4095 ?name=fred;age=24;favorite_color=3
4097 Semicolon-delimited query strings are always accepted, but will not be
4098 emitted by self_url() and query_string() unless the -newstyle_urls
4099 pragma is specified.
4101 This became the default in version 2.64.
4103 =item -oldstyle_urls
4105 Separate the name=value pairs in CGI parameter query strings with
4106 ampersands rather than semicolons. This is no longer the default.
4110 This overrides the autoloader so that any function in your program
4111 that is not recognized is referred to CGI.pm for possible evaluation.
4112 This allows you to use all the CGI.pm functions without adding them to
4113 your symbol table, which is of concern for mod_perl users who are
4114 worried about memory consumption. I<Warning:> when
4115 I<-autoload> is in effect, you cannot use "poetry mode"
4116 (functions without the parenthesis). Use I<hr()> rather
4117 than I<hr>, or add something like I<use subs qw/hr p header/>
4118 to the top of your script.
4122 This turns off the command-line processing features. If you want to
4123 run a CGI.pm script from the command line to produce HTML, and you
4124 don't want it to read CGI parameters from the command line or STDIN,
4125 then use this pragma:
4127 use CGI qw(-no_debug :standard);
4131 This turns on full debugging. In addition to reading CGI arguments
4132 from the command-line processing, CGI.pm will pause and try to read
4133 arguments from STDIN, producing the message "(offline mode: enter
4134 name=value pairs on standard input)" features.
4136 See the section on debugging for more details.
4138 =item -private_tempfiles
4140 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4141 file to a temporary directory, then deletes the file when done.
4142 However, this opens the risk of eavesdropping as described in the file
4143 upload section. Another CGI script author could peek at this data
4144 during the upload, even if it is confidential information. On Unix
4145 systems, the -private_tempfiles pragma will cause the temporary file
4146 to be unlinked as soon as it is opened and before any data is written
4147 into it, reducing, but not eliminating the risk of eavesdropping
4148 (there is still a potential race condition). To make life harder for
4149 the attacker, the program chooses tempfile names by calculating a 32
4150 bit checksum of the incoming HTTP headers.
4152 To ensure that the temporary file cannot be read by other CGI scripts,
4153 use suEXEC or a CGI wrapper program to run your script. The temporary
4154 file is created with mode 0600 (neither world nor group readable).
4156 The temporary directory is selected using the following algorithm:
4158 1. if the current user (e.g. "nobody") has a directory named
4159 "tmp" in its home directory, use that (Unix systems only).
4161 2. if the environment variable TMPDIR exists, use the location
4164 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4165 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4167 Each of these locations is checked that it is a directory and is
4168 writable. If not, the algorithm tries the next choice.
4172 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4174 Many of the methods generate HTML tags. As described below, tag
4175 functions automatically generate both the opening and closing tags.
4178 print h1('Level 1 Header');
4182 <H1>Level 1 Header</H1>
4184 There will be some times when you want to produce the start and end
4185 tags yourself. In this case, you can use the form start_I<tag_name>
4186 and end_I<tag_name>, as in:
4188 print start_h1,'Level 1 Header',end_h1;
4190 With a few exceptions (described below), start_I<tag_name> and
4191 end_I<tag_name> functions are not generated automatically when you
4192 I<use CGI>. However, you can specify the tags you want to generate
4193 I<start/end> functions for by putting an asterisk in front of their
4194 name, or, alternatively, requesting either "start_I<tag_name>" or
4195 "end_I<tag_name>" in the import list.
4199 use CGI qw/:standard *table start_ul/;
4201 In this example, the following functions are generated in addition to
4206 =item 1. start_table() (generates a <TABLE> tag)
4208 =item 2. end_table() (generates a </TABLE> tag)
4210 =item 3. start_ul() (generates a <UL> tag)
4212 =item 4. end_ul() (generates a </UL> tag)
4216 =head1 GENERATING DYNAMIC DOCUMENTS
4218 Most of CGI.pm's functions deal with creating documents on the fly.
4219 Generally you will produce the HTTP header first, followed by the
4220 document itself. CGI.pm provides functions for generating HTTP
4221 headers of various types as well as for generating HTML. For creating
4222 GIF images, see the GD.pm module.
4224 Each of these functions produces a fragment of HTML or HTTP which you
4225 can print out directly so that it displays in the browser window,
4226 append to a string, or save to a file for later use.
4228 =head2 CREATING A STANDARD HTTP HEADER:
4230 Normally the first thing you will do in any CGI script is print out an
4231 HTTP header. This tells the browser what type of document to expect,
4232 and gives other optional information, such as the language, expiration
4233 date, and whether to cache the document. The header can also be
4234 manipulated for special purposes, such as server push and pay per view
4237 print $query->header;
4241 print $query->header('image/gif');
4245 print $query->header('text/html','204 No response');
4249 print $query->header(-type=>'image/gif',
4251 -status=>'402 Payment required',
4255 -attachment=>'foo.gif',
4258 header() returns the Content-type: header. You can provide your own
4259 MIME type if you choose, otherwise it defaults to text/html. An
4260 optional second parameter specifies the status code and a human-readable
4261 message. For example, you can specify 204, "No response" to create a
4262 script that tells the browser to do nothing at all.
4264 The last example shows the named argument style for passing arguments
4265 to the CGI methods using named parameters. Recognized parameters are
4266 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
4267 parameters will be stripped of their initial hyphens and turned into
4268 header fields, allowing you to specify any HTTP header you desire.
4269 Internal underscores will be turned into hyphens:
4271 print $query->header(-Content_length=>3002);
4273 Most browsers will not cache the output from CGI scripts. Every time
4274 the browser reloads the page, the script is invoked anew. You can
4275 change this behavior with the B<-expires> parameter. When you specify
4276 an absolute or relative expiration interval with this parameter, some
4277 browsers and proxy servers will cache the script's output until the
4278 indicated expiration date. The following forms are all valid for the
4281 +30s 30 seconds from now
4282 +10m ten minutes from now
4283 +1h one hour from now
4284 -1d yesterday (i.e. "ASAP!")
4287 +10y in ten years time
4288 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
4290 The B<-cookie> parameter generates a header that tells the browser to provide
4291 a "magic cookie" during all subsequent transactions with your script.
4292 Netscape cookies have a special format that includes interesting attributes
4293 such as expiration time. Use the cookie() method to create and retrieve
4296 The B<-nph> parameter, if set to a true value, will issue the correct
4297 headers to work with a NPH (no-parse-header) script. This is important
4298 to use with certain servers that expect all their scripts to be NPH.
4300 The B<-charset> parameter can be used to control the character set
4301 sent to the browser. If not provided, defaults to ISO-8859-1. As a
4302 side effect, this sets the charset() method as well.
4304 The B<-attachment> parameter can be used to turn the page into an
4305 attachment. Instead of displaying the page, some browsers will prompt
4306 the user to save it to disk. The value of the argument is the
4307 suggested name for the saved file. In order for this to work, you may
4308 have to set the B<-type> to "application/octet-stream".
4310 =head2 GENERATING A REDIRECTION HEADER
4312 print $query->redirect('http://somewhere.else/in/movie/land');
4314 Sometimes you don't want to produce a document yourself, but simply
4315 redirect the browser elsewhere, perhaps choosing a URL based on the
4316 time of day or the identity of the user.
4318 The redirect() function redirects the browser to a different URL. If
4319 you use redirection like this, you should B<not> print out a header as
4322 One hint I can offer is that relative links may not work correctly
4323 when you generate a redirection to another document on your site.
4324 This is due to a well-intentioned optimization that some servers use.
4325 The solution to this is to use the full URL (including the http: part)
4326 of the document you are redirecting to.
4328 You can also use named arguments:
4330 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4333 The B<-nph> parameter, if set to a true value, will issue the correct
4334 headers to work with a NPH (no-parse-header) script. This is important
4335 to use with certain servers, such as Microsoft Internet Explorer, which
4336 expect all their scripts to be NPH.
4338 =head2 CREATING THE HTML DOCUMENT HEADER
4340 print $query->start_html(-title=>'Secrets of the Pyramids',
4341 -author=>'fred@capricorn.org',
4344 -meta=>{'keywords'=>'pharaoh secret mummy',
4345 'copyright'=>'copyright 1996 King Tut'},
4346 -style=>{'src'=>'/styles/style1.css'},
4349 After creating the HTTP header, most CGI scripts will start writing
4350 out an HTML document. The start_html() routine creates the top of the
4351 page, along with a lot of optional information that controls the
4352 page's appearance and behavior.
4354 This method returns a canned HTML header and the opening <BODY> tag.
4355 All parameters are optional. In the named parameter form, recognized
4356 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4357 (see below for the explanation). Any additional parameters you
4358 provide, such as the Netscape unofficial BGCOLOR attribute, are added
4359 to the <BODY> tag. Additional parameters must be proceeded by a
4362 The argument B<-xbase> allows you to provide an HREF for the <BASE> tag
4363 different from the current location, as in
4365 -xbase=>"http://home.mcom.com/"
4367 All relative links will be interpreted relative to this tag.
4369 The argument B<-target> allows you to provide a default target frame
4370 for all the links and fill-out forms on the page. B<This is a
4371 non-standard HTTP feature which only works with Netscape browsers!>
4372 See the Netscape documentation on frames for details of how to
4375 -target=>"answer_window"
4377 All relative links will be interpreted relative to this tag.
4378 You add arbitrary meta information to the header with the B<-meta>
4379 argument. This argument expects a reference to an associative array
4380 containing name/value pairs of meta information. These will be turned
4381 into a series of header <META> tags that look something like this:
4383 <META NAME="keywords" CONTENT="pharaoh secret mummy">
4384 <META NAME="description" CONTENT="copyright 1996 King Tut">
4386 To create an HTTP-EQUIV type of <META> tag, use B<-head>, described
4389 The B<-style> argument is used to incorporate cascading stylesheets
4390 into your code. See the section on CASCADING STYLESHEETS for more
4393 The B<-lang> argument is used to incorporate a language attribute into
4394 the <HTML> tag. The default if not specified is "en-US" for US
4395 English. For example:
4397 print $q->start_html(-lang=>'fr-CA');
4399 You can place other arbitrary HTML elements to the <HEAD> section with the
4400 B<-head> tag. For example, to place the rarely-used <LINK> element in the
4401 head section, use this:
4403 print start_html(-head=>Link({-rel=>'next',
4404 -href=>'http://www.capricorn.com/s2.html'}));
4406 To incorporate multiple HTML elements into the <HEAD> section, just pass an
4409 print start_html(-head=>[
4411 -href=>'http://www.capricorn.com/s2.html'}),
4412 Link({-rel=>'previous',
4413 -href=>'http://www.capricorn.com/s1.html'})
4417 And here's how to create an HTTP-EQUIV <META> tag:
4419 print start_html(-head=>meta({-http_equiv => 'Content-Type',
4420 -content => 'text/html'}))
4423 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4424 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4425 to add Netscape JavaScript calls to your pages. B<-script> should
4426 point to a block of text containing JavaScript function definitions.
4427 This block will be placed within a <SCRIPT> block inside the HTML (not
4428 HTTP) header. The block is placed in the header in order to give your
4429 page a fighting chance of having all its JavaScript functions in place
4430 even if the user presses the stop button before the page has loaded
4431 completely. CGI.pm attempts to format the script in such a way that
4432 JavaScript-naive browsers will not choke on the code: unfortunately
4433 there are some browsers, such as Chimera for Unix, that get confused
4436 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4437 code to execute when the page is respectively opened and closed by the
4438 browser. Usually these parameters are calls to functions defined in the
4442 print $query->header;
4444 // Ask a silly question
4445 function riddle_me_this() {
4446 var r = prompt("What walks on four legs in the morning, " +
4447 "two legs in the afternoon, " +
4448 "and three legs in the evening?");
4451 // Get a silly answer
4452 function response(answer) {
4453 if (answer == "man")
4454 alert("Right you are!");
4456 alert("Wrong! Guess again.");
4459 print $query->start_html(-title=>'The Riddle of the Sphinx',
4462 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4463 browsers that do not have JavaScript (or browsers where JavaScript is turned
4466 Netscape 3.0 recognizes several attributes of the <SCRIPT> tag,
4467 including LANGUAGE and SRC. The latter is particularly interesting,
4468 as it allows you to keep the JavaScript code in a file or CGI script
4469 rather than cluttering up each page with the source. To use these
4470 attributes pass a HASH reference in the B<-script> parameter containing
4471 one or more of -language, -src, or -code:
4473 print $q->start_html(-title=>'The Riddle of the Sphinx',
4474 -script=>{-language=>'JAVASCRIPT',
4475 -src=>'/javascript/sphinx.js'}
4478 print $q->(-title=>'The Riddle of the Sphinx',
4479 -script=>{-language=>'PERLSCRIPT',
4480 -code=>'print "hello world!\n;"'}
4484 A final feature allows you to incorporate multiple <SCRIPT> sections into the
4485 header. Just pass the list of script sections as an array reference.
4486 this allows you to specify different source files for different dialects
4487 of JavaScript. Example:
4489 print $q->start_html(-title=>'The Riddle of the Sphinx',
4491 { -language => 'JavaScript1.0',
4492 -src => '/javascript/utilities10.js'
4494 { -language => 'JavaScript1.1',
4495 -src => '/javascript/utilities11.js'
4497 { -language => 'JavaScript1.2',
4498 -src => '/javascript/utilities12.js'
4500 { -language => 'JavaScript28.2',
4501 -src => '/javascript/utilities219.js'
4507 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4511 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4513 for more information about JavaScript.
4515 The old-style positional parameters are as follows:
4519 =item B<Parameters:>
4527 The author's e-mail address (will create a <LINK REV="MADE"> tag if present
4531 A 'true' flag if you want to include a <BASE> tag in the header. This
4532 helps resolve relative addresses to absolute ones when the document is moved,
4533 but makes the document hierarchy non-portable. Use with care!
4537 Any other parameters you want to include in the <BODY> tag. This is a good
4538 place to put Netscape extensions, such as colors and wallpaper patterns.
4542 =head2 ENDING THE HTML DOCUMENT:
4544 print $query->end_html
4546 This ends an HTML document by printing the </BODY></HTML> tags.
4548 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4550 $myself = $query->self_url;
4551 print q(<A HREF="$myself">I'm talking to myself.</A>);
4553 self_url() will return a URL, that, when selected, will reinvoke
4554 this script with all its state information intact. This is most
4555 useful when you want to jump around within the document using
4556 internal anchors but you don't want to disrupt the current contents
4557 of the form(s). Something like this will do the trick.
4559 $myself = $query->self_url;
4560 print "<A HREF=$myself#table1>See table 1</A>";
4561 print "<A HREF=$myself#table2>See table 2</A>";
4562 print "<A HREF=$myself#yourself>See for yourself</A>";
4564 If you want more control over what's returned, using the B<url()>
4567 You can also retrieve the unprocessed query string with query_string():
4569 $the_string = $query->query_string;
4571 =head2 OBTAINING THE SCRIPT'S URL
4573 $full_url = $query->url();
4574 $full_url = $query->url(-full=>1); #alternative syntax
4575 $relative_url = $query->url(-relative=>1);
4576 $absolute_url = $query->url(-absolute=>1);
4577 $url_with_path = $query->url(-path_info=>1);
4578 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4579 $netloc = $query->url(-base => 1);
4581 B<url()> returns the script's URL in a variety of formats. Called
4582 without any arguments, it returns the full form of the URL, including
4583 host name and port number
4585 http://your.host.com/path/to/script.cgi
4587 You can modify this format with the following named arguments:
4593 If true, produce an absolute URL, e.g.
4599 Produce a relative URL. This is useful if you want to reinvoke your
4600 script with different parameters. For example:
4606 Produce the full URL, exactly as if called without any arguments.
4607 This overrides the -relative and -absolute arguments.
4609 =item B<-path> (B<-path_info>)
4611 Append the additional path information to the URL. This can be
4612 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
4613 is provided as a synonym.
4615 =item B<-query> (B<-query_string>)
4617 Append the query string to the URL. This can be combined with
4618 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
4623 Generate just the protocol and net location, as in http://www.foo.com:8000
4627 =head2 MIXING POST AND URL PARAMETERS
4629 $color = $query->url_param('color');
4631 It is possible for a script to receive CGI parameters in the URL as
4632 well as in the fill-out form by creating a form that POSTs to a URL
4633 containing a query string (a "?" mark followed by arguments). The
4634 B<param()> method will always return the contents of the POSTed
4635 fill-out form, ignoring the URL's query string. To retrieve URL
4636 parameters, call the B<url_param()> method. Use it in the same way as
4637 B<param()>. The main difference is that it allows you to read the
4638 parameters, but not set them.
4641 Under no circumstances will the contents of the URL query string
4642 interfere with similarly-named CGI parameters in POSTed forms. If you
4643 try to mix a URL query string with a form submitted with the GET
4644 method, the results will not be what you expect.
4646 =head1 CREATING STANDARD HTML ELEMENTS:
4648 CGI.pm defines general HTML shortcut methods for most, if not all of
4649 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
4650 HTML element and return a fragment of HTML text that you can then
4651 print or manipulate as you like. Each shortcut returns a fragment of
4652 HTML code that you can append to a string, save to a file, or, most
4653 commonly, print out so that it displays in the browser window.
4655 This example shows how to use the HTML methods:
4658 print $q->blockquote(
4659 "Many years ago on the island of",
4660 $q->a({href=>"http://crete.org/"},"Crete"),
4661 "there lived a Minotaur named",
4662 $q->strong("Fred."),
4666 This results in the following HTML code (extra newlines have been
4667 added for readability):
4670 Many years ago on the island of
4671 <a HREF="http://crete.org/">Crete</a> there lived
4672 a minotaur named <strong>Fred.</strong>
4676 If you find the syntax for calling the HTML shortcuts awkward, you can
4677 import them into your namespace and dispense with the object syntax
4678 completely (see the next section for more details):
4680 use CGI ':standard';
4682 "Many years ago on the island of",
4683 a({href=>"http://crete.org/"},"Crete"),
4684 "there lived a minotaur named",
4689 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
4691 The HTML methods will accept zero, one or multiple arguments. If you
4692 provide no arguments, you get a single tag:
4696 If you provide one or more string arguments, they are concatenated
4697 together with spaces and placed between opening and closing tags:
4699 print h1("Chapter","1"); # <H1>Chapter 1</H1>"
4701 If the first argument is an associative array reference, then the keys
4702 and values of the associative array become the HTML tag's attributes:
4704 print a({-href=>'fred.html',-target=>'_new'},
4705 "Open a new frame");
4707 <A HREF="fred.html",TARGET="_new">Open a new frame</A>
4709 You may dispense with the dashes in front of the attribute names if
4712 print img {src=>'fred.gif',align=>'LEFT'};
4714 <IMG ALIGN="LEFT" SRC="fred.gif">
4716 Sometimes an HTML tag attribute has no argument. For example, ordered
4717 lists can be marked as COMPACT. The syntax for this is an argument that
4718 that points to an undef string:
4720 print ol({compact=>undef},li('one'),li('two'),li('three'));
4722 Prior to CGI.pm version 2.41, providing an empty ('') string as an
4723 attribute argument was the same as providing undef. However, this has
4724 changed in order to accommodate those who want to create tags of the form
4725 <IMG ALT="">. The difference is shown in these two pieces of code:
4728 img({alt=>undef}) <IMG ALT>
4729 img({alt=>''}) <IMT ALT="">
4731 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
4733 One of the cool features of the HTML shortcuts is that they are
4734 distributive. If you give them an argument consisting of a
4735 B<reference> to a list, the tag will be distributed across each
4736 element of the list. For example, here's one way to make an ordered
4740 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
4743 This example will result in HTML output that looks like this:
4746 <LI TYPE="disc">Sneezy</LI>
4747 <LI TYPE="disc">Doc</LI>
4748 <LI TYPE="disc">Sleepy</LI>
4749 <LI TYPE="disc">Happy</LI>
4752 This is extremely useful for creating tables. For example:
4754 print table({-border=>undef},
4755 caption('When Should You Eat Your Vegetables?'),
4756 Tr({-align=>CENTER,-valign=>TOP},
4758 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
4759 td(['Tomatoes' , 'no', 'yes', 'yes']),
4760 td(['Broccoli' , 'no', 'no', 'yes']),
4761 td(['Onions' , 'yes','yes', 'yes'])
4766 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
4768 Consider this bit of code:
4770 print blockquote(em('Hi'),'mom!'));
4772 It will ordinarily return the string that you probably expect, namely:
4774 <BLOCKQUOTE><EM>Hi</EM> mom!</BLOCKQUOTE>
4776 Note the space between the element "Hi" and the element "mom!".
4777 CGI.pm puts the extra space there using array interpolation, which is
4778 controlled by the magic $" variable. Sometimes this extra space is
4779 not what you want, for example, when you are trying to align a series
4780 of images. In this case, you can simply change the value of $" to an
4785 print blockquote(em('Hi'),'mom!'));
4788 I suggest you put the code in a block as shown here. Otherwise the
4789 change to $" will affect all subsequent code until you explicitly
4792 =head2 NON-STANDARD HTML SHORTCUTS
4794 A few HTML tags don't follow the standard pattern for various
4797 B<comment()> generates an HTML comment (<!-- comment -->). Call it
4800 print comment('here is my comment');
4802 Because of conflicts with built-in Perl functions, the following functions
4803 begin with initial caps:
4812 In addition, start_html(), end_html(), start_form(), end_form(),
4813 start_multipart_form() and all the fill-out form tags are special.
4814 See their respective sections.
4816 =head2 AUTOESCAPING HTML
4818 By default, all HTML that is emitted by the form-generating functions
4819 is passed through a function called escapeHTML():
4823 =item $escaped_string = escapeHTML("unescaped string");
4825 Escape HTML formatting characters in a string.
4829 Provided that you have specified a character set of ISO-8859-1 (the
4830 default), the standard HTML escaping rules will be used. The "<"
4831 character becomes "<", ">" becomes ">", "&" becomes "&", and
4832 the quote character becomes """. In addition, the hexadecimal
4833 0x8b and 0x9b characters, which many windows-based browsers interpret
4834 as the left and right angle-bracket characters, are replaced by their
4835 numeric HTML entities ("‹" and "›"). If you manually change
4836 the charset, either by calling the charset() method explicitly or by
4837 passing a -charset argument to header(), then B<all> characters will
4838 be replaced by their numeric entities, since CGI.pm has no lookup
4839 table for all the possible encodings.
4841 The automatic escaping does not apply to other shortcuts, such as
4842 h1(). You should call escapeHTML() yourself on untrusted data in
4843 order to protect your pages against nasty tricks that people may enter
4844 into guestbooks, etc.. To change the character set, use charset().
4845 To turn autoescaping off completely, use autoescape():
4849 =item $charset = charset([$charset]);
4851 Get or set the current character set.
4853 =item $flag = autoEscape([$flag]);
4855 Get or set the value of the autoescape flag.
4859 =head2 PRETTY-PRINTING HTML
4861 By default, all the HTML produced by these functions comes out as one
4862 long line without carriage returns or indentation. This is yuck, but
4863 it does reduce the size of the documents by 10-20%. To get
4864 pretty-printed output, please use L<CGI::Pretty>, a subclass
4865 contributed by Brian Paulsen.
4867 =head1 CREATING FILL-OUT FORMS:
4869 I<General note> The various form-creating methods all return strings
4870 to the caller, containing the tag or tags that will create the requested
4871 form element. You are responsible for actually printing out these strings.
4872 It's set up this way so that you can place formatting tags
4873 around the form elements.
4875 I<Another note> The default values that you specify for the forms are only
4876 used the B<first> time the script is invoked (when there is no query
4877 string). On subsequent invocations of the script (when there is a query
4878 string), the former values are used even if they are blank.
4880 If you want to change the value of a field from its previous value, you have two
4883 (1) call the param() method to set it.
4885 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
4886 This forces the default value to be used, regardless of the previous value:
4888 print $query->textfield(-name=>'field_name',
4889 -default=>'starting value',
4894 I<Yet another note> By default, the text and labels of form elements are
4895 escaped according to HTML rules. This means that you can safely use
4896 "<CLICK ME>" as the label for a button. However, it also interferes with
4897 your ability to incorporate special HTML character sequences, such as Á,
4898 into your fields. If you wish to turn off automatic escaping, call the
4899 autoEscape() method with a false value immediately after creating the CGI object:
4902 $query->autoEscape(undef);
4904 =head2 CREATING AN ISINDEX TAG
4906 print $query->isindex(-action=>$action);
4910 print $query->isindex($action);
4912 Prints out an <ISINDEX> tag. Not very exciting. The parameter
4913 -action specifies the URL of the script to process the query. The
4914 default is to process the query with the current script.
4916 =head2 STARTING AND ENDING A FORM
4918 print $query->start_form(-method=>$method,
4920 -enctype=>$encoding);
4921 <... various form stuff ...>
4922 print $query->endform;
4926 print $query->start_form($method,$action,$encoding);
4927 <... various form stuff ...>
4928 print $query->endform;
4930 start_form() will return a <FORM> tag with the optional method,
4931 action and form encoding that you specify. The defaults are:
4935 enctype: application/x-www-form-urlencoded
4937 endform() returns the closing </FORM> tag.
4939 Start_form()'s enctype argument tells the browser how to package the various
4940 fields of the form before sending the form to the server. Two
4941 values are possible:
4943 B<Note:> This method was previously named startform(), and startform()
4944 is still recognized as an alias.
4948 =item B<application/x-www-form-urlencoded>
4950 This is the older type of encoding used by all browsers prior to
4951 Netscape 2.0. It is compatible with many CGI scripts and is
4952 suitable for short fields containing text data. For your
4953 convenience, CGI.pm stores the name of this encoding
4954 type in B<&CGI::URL_ENCODED>.
4956 =item B<multipart/form-data>
4958 This is the newer type of encoding introduced by Netscape 2.0.
4959 It is suitable for forms that contain very large fields or that
4960 are intended for transferring binary data. Most importantly,
4961 it enables the "file upload" feature of Netscape 2.0 forms. For
4962 your convenience, CGI.pm stores the name of this encoding type
4963 in B<&CGI::MULTIPART>
4965 Forms that use this type of encoding are not easily interpreted
4966 by CGI scripts unless they use CGI.pm or another library designed
4971 For compatibility, the start_form() method uses the older form of
4972 encoding by default. If you want to use the newer form of encoding
4973 by default, you can call B<start_multipart_form()> instead of
4976 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
4977 for use with JavaScript. The -name parameter gives the
4978 form a name so that it can be identified and manipulated by
4979 JavaScript functions. -onSubmit should point to a JavaScript
4980 function that will be executed just before the form is submitted to your
4981 server. You can use this opportunity to check the contents of the form
4982 for consistency and completeness. If you find something wrong, you
4983 can put up an alert box or maybe fix things up yourself. You can
4984 abort the submission by returning false from this function.
4986 Usually the bulk of JavaScript functions are defined in a <SCRIPT>
4987 block in the HTML header and -onSubmit points to one of these function
4988 call. See start_html() for details.
4990 =head2 CREATING A TEXT FIELD
4992 print $query->textfield(-name=>'field_name',
4993 -default=>'starting value',
4998 print $query->textfield('field_name','starting value',50,80);
5000 textfield() will return a text input field.
5008 The first parameter is the required name for the field (-name).
5012 The optional second parameter is the default starting value for the field
5013 contents (-default).
5017 The optional third parameter is the size of the field in
5022 The optional fourth parameter is the maximum number of characters the
5023 field will accept (-maxlength).
5027 As with all these methods, the field will be initialized with its
5028 previous contents from earlier invocations of the script.
5029 When the form is processed, the value of the text field can be
5032 $value = $query->param('foo');
5034 If you want to reset it from its initial value after the script has been
5035 called once, you can do so like this:
5037 $query->param('foo',"I'm taking over this value!");
5039 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
5040 value, you can force its current value by using the -override (alias -force)
5043 print $query->textfield(-name=>'field_name',
5044 -default=>'starting value',
5049 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
5050 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
5051 parameters to register JavaScript event handlers. The onChange
5052 handler will be called whenever the user changes the contents of the
5053 text field. You can do text validation if you like. onFocus and
5054 onBlur are called respectively when the insertion point moves into and
5055 out of the text field. onSelect is called when the user changes the
5056 portion of the text that is selected.
5058 =head2 CREATING A BIG TEXT FIELD
5060 print $query->textarea(-name=>'foo',
5061 -default=>'starting value',
5067 print $query->textarea('foo','starting value',10,50);
5069 textarea() is just like textfield, but it allows you to specify
5070 rows and columns for a multiline text entry box. You can provide
5071 a starting value for the field, which can be long and contain
5074 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
5075 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
5076 recognized. See textfield().
5078 =head2 CREATING A PASSWORD FIELD
5080 print $query->password_field(-name=>'secret',
5081 -value=>'starting value',
5086 print $query->password_field('secret','starting value',50,80);
5088 password_field() is identical to textfield(), except that its contents
5089 will be starred out on the web page.
5091 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5092 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5093 recognized. See textfield().
5095 =head2 CREATING A FILE UPLOAD FIELD
5097 print $query->filefield(-name=>'uploaded_file',
5098 -default=>'starting value',
5103 print $query->filefield('uploaded_file','starting value',50,80);
5105 filefield() will return a file upload field for Netscape 2.0 browsers.
5106 In order to take full advantage of this I<you must use the new
5107 multipart encoding scheme> for the form. You can do this either
5108 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5109 or by calling the new method B<start_multipart_form()> instead of
5110 vanilla B<start_form()>.
5118 The first parameter is the required name for the field (-name).
5122 The optional second parameter is the starting value for the field contents
5123 to be used as the default file name (-default).
5125 For security reasons, browsers don't pay any attention to this field,
5126 and so the starting value will always be blank. Worse, the field
5127 loses its "sticky" behavior and forgets its previous contents. The
5128 starting value field is called for in the HTML specification, however,
5129 and possibly some browser will eventually provide support for it.
5133 The optional third parameter is the size of the field in
5138 The optional fourth parameter is the maximum number of characters the
5139 field will accept (-maxlength).
5143 When the form is processed, you can retrieve the entered filename
5146 $filename = $query->param('uploaded_file');
5148 Different browsers will return slightly different things for the
5149 name. Some browsers return the filename only. Others return the full
5150 path to the file, using the path conventions of the user's machine.
5151 Regardless, the name returned is always the name of the file on the
5152 I<user's> machine, and is unrelated to the name of the temporary file
5153 that CGI.pm creates during upload spooling (see below).
5155 The filename returned is also a file handle. You can read the contents
5156 of the file using standard Perl file reading calls:
5158 # Read a text file and print it out
5159 while (<$filename>) {
5163 # Copy a binary file to somewhere safe
5164 open (OUTFILE,">>/usr/local/web/users/feedback");
5165 while ($bytesread=read($filename,$buffer,1024)) {
5166 print OUTFILE $buffer;
5169 However, there are problems with the dual nature of the upload fields.
5170 If you C<use strict>, then Perl will complain when you try to use a
5171 string as a filehandle. You can get around this by placing the file
5172 reading code in a block containing the C<no strict> pragma. More
5173 seriously, it is possible for the remote user to type garbage into the
5174 upload field, in which case what you get from param() is not a
5175 filehandle at all, but a string.
5177 To be safe, use the I<upload()> function (new in version 2.47). When
5178 called with the name of an upload field, I<upload()> returns a
5179 filehandle, or undef if the parameter is not a valid filehandle.
5181 $fh = $query->upload('uploaded_file');
5186 In an array context, upload() will return an array of filehandles.
5187 This makes it possible to create forms that use the same name for
5188 multiple upload fields.
5190 This is the recommended idiom.
5192 When a file is uploaded the browser usually sends along some
5193 information along with it in the format of headers. The information
5194 usually includes the MIME content type. Future browsers may send
5195 other information as well (such as modification date and size). To
5196 retrieve this information, call uploadInfo(). It returns a reference to
5197 an associative array containing all the document headers.
5199 $filename = $query->param('uploaded_file');
5200 $type = $query->uploadInfo($filename)->{'Content-Type'};
5201 unless ($type eq 'text/html') {
5202 die "HTML FILES ONLY!";
5205 If you are using a machine that recognizes "text" and "binary" data
5206 modes, be sure to understand when and how to use them (see the Camel book).
5207 Otherwise you may find that binary files are corrupted during file
5210 There are occasionally problems involving parsing the uploaded file.
5211 This usually happens when the user presses "Stop" before the upload is
5212 finished. In this case, CGI.pm will return undef for the name of the
5213 uploaded file and set I<cgi_error()> to the string "400 Bad request
5214 (malformed multipart POST)". This error message is designed so that
5215 you can incorporate it into a status code to be sent to the browser.
5218 $file = $query->upload('uploaded_file');
5219 if (!$file && $query->cgi_error) {
5220 print $query->header(-status=>$query->cgi_error);
5224 You are free to create a custom HTML page to complain about the error,
5227 If you are using CGI.pm on a Windows platform and find that binary
5228 files get slightly larger when uploaded but that text files remain the
5229 same, then you have forgotten to activate binary mode on the output
5230 filehandle. Be sure to call binmode() on any handle that you create
5231 to write the uploaded file to disk.
5233 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5234 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5235 recognized. See textfield() for details.
5237 =head2 CREATING A POPUP MENU
5239 print $query->popup_menu('menu_name',
5240 ['eenie','meenie','minie'],
5245 %labels = ('eenie'=>'your first choice',
5246 'meenie'=>'your second choice',
5247 'minie'=>'your third choice');
5248 print $query->popup_menu('menu_name',
5249 ['eenie','meenie','minie'],
5252 -or (named parameter style)-
5254 print $query->popup_menu(-name=>'menu_name',
5255 -values=>['eenie','meenie','minie'],
5259 popup_menu() creates a menu.
5265 The required first argument is the menu's name (-name).
5269 The required second argument (-values) is an array B<reference>
5270 containing the list of menu items in the menu. You can pass the
5271 method an anonymous array, as shown in the example, or a reference to
5272 a named array, such as "\@foo".
5276 The optional third parameter (-default) is the name of the default
5277 menu choice. If not specified, the first item will be the default.
5278 The values of the previous choice will be maintained across queries.
5282 The optional fourth parameter (-labels) is provided for people who
5283 want to use different values for the user-visible label inside the
5284 popup menu nd the value returned to your script. It's a pointer to an
5285 associative array relating menu values to user-visible labels. If you
5286 leave this parameter blank, the menu values will be displayed by
5287 default. (You can also leave a label undefined if you want to).
5291 When the form is processed, the selected value of the popup menu can
5294 $popup_menu_value = $query->param('menu_name');
5296 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
5297 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5298 B<-onBlur>. See the textfield() section for details on when these
5299 handlers are called.
5301 =head2 CREATING A SCROLLING LIST
5303 print $query->scrolling_list('list_name',
5304 ['eenie','meenie','minie','moe'],
5305 ['eenie','moe'],5,'true');
5308 print $query->scrolling_list('list_name',
5309 ['eenie','meenie','minie','moe'],
5310 ['eenie','moe'],5,'true',
5315 print $query->scrolling_list(-name=>'list_name',
5316 -values=>['eenie','meenie','minie','moe'],
5317 -default=>['eenie','moe'],
5322 scrolling_list() creates a scrolling list.
5326 =item B<Parameters:>
5330 The first and second arguments are the list name (-name) and values
5331 (-values). As in the popup menu, the second argument should be an
5336 The optional third argument (-default) can be either a reference to a
5337 list containing the values to be selected by default, or can be a
5338 single value to select. If this argument is missing or undefined,
5339 then nothing is selected when the list first appears. In the named
5340 parameter version, you can use the synonym "-defaults" for this
5345 The optional fourth argument is the size of the list (-size).
5349 The optional fifth argument can be set to true to allow multiple
5350 simultaneous selections (-multiple). Otherwise only one selection
5351 will be allowed at a time.
5355 The optional sixth argument is a pointer to an associative array
5356 containing long user-visible labels for the list items (-labels).
5357 If not provided, the values will be displayed.
5359 When this form is processed, all selected list items will be returned as
5360 a list under the parameter name 'list_name'. The values of the
5361 selected items can be retrieved with:
5363 @selected = $query->param('list_name');
5367 JAVASCRIPTING: scrolling_list() recognizes the following event
5368 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5369 and B<-onBlur>. See textfield() for the description of when these
5370 handlers are called.
5372 =head2 CREATING A GROUP OF RELATED CHECKBOXES
5374 print $query->checkbox_group(-name=>'group_name',
5375 -values=>['eenie','meenie','minie','moe'],
5376 -default=>['eenie','moe'],
5380 print $query->checkbox_group('group_name',
5381 ['eenie','meenie','minie','moe'],
5382 ['eenie','moe'],'true',\%labels);
5384 HTML3-COMPATIBLE BROWSERS ONLY:
5386 print $query->checkbox_group(-name=>'group_name',
5387 -values=>['eenie','meenie','minie','moe'],
5388 -rows=2,-columns=>2);
5391 checkbox_group() creates a list of checkboxes that are related
5396 =item B<Parameters:>
5400 The first and second arguments are the checkbox name and values,
5401 respectively (-name and -values). As in the popup menu, the second
5402 argument should be an array reference. These values are used for the
5403 user-readable labels printed next to the checkboxes as well as for the
5404 values passed to your script in the query string.
5408 The optional third argument (-default) can be either a reference to a
5409 list containing the values to be checked by default, or can be a
5410 single value to checked. If this argument is missing or undefined,
5411 then nothing is selected when the list first appears.
5415 The optional fourth argument (-linebreak) can be set to true to place
5416 line breaks between the checkboxes so that they appear as a vertical
5417 list. Otherwise, they will be strung together on a horizontal line.
5421 The optional fifth argument is a pointer to an associative array
5422 relating the checkbox values to the user-visible labels that will
5423 be printed next to them (-labels). If not provided, the values will
5424 be used as the default.
5428 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5429 the optional parameters B<-rows>, and B<-columns>. These parameters
5430 cause checkbox_group() to return an HTML3 compatible table containing
5431 the checkbox group formatted with the specified number of rows and
5432 columns. You can provide just the -columns parameter if you wish;
5433 checkbox_group will calculate the correct number of rows for you.
5435 To include row and column headings in the returned table, you
5436 can use the B<-rowheaders> and B<-colheaders> parameters. Both
5437 of these accept a pointer to an array of headings to use.
5438 The headings are just decorative. They don't reorganize the
5439 interpretation of the checkboxes -- they're still a single named
5444 When the form is processed, all checked boxes will be returned as
5445 a list under the parameter name 'group_name'. The values of the
5446 "on" checkboxes can be retrieved with:
5448 @turned_on = $query->param('group_name');
5450 The value returned by checkbox_group() is actually an array of button
5451 elements. You can capture them and use them within tables, lists,
5452 or in other creative ways:
5454 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
5455 &use_in_creative_way(@h);
5457 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
5458 parameter. This specifies a JavaScript code fragment or
5459 function call to be executed every time the user clicks on
5460 any of the buttons in the group. You can retrieve the identity
5461 of the particular button clicked on using the "this" variable.
5463 =head2 CREATING A STANDALONE CHECKBOX
5465 print $query->checkbox(-name=>'checkbox_name',
5466 -checked=>'checked',
5468 -label=>'CLICK ME');
5472 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
5474 checkbox() is used to create an isolated checkbox that isn't logically
5475 related to any others.
5479 =item B<Parameters:>
5483 The first parameter is the required name for the checkbox (-name). It
5484 will also be used for the user-readable label printed next to the
5489 The optional second parameter (-checked) specifies that the checkbox
5490 is turned on by default. Synonyms are -selected and -on.
5494 The optional third parameter (-value) specifies the value of the
5495 checkbox when it is checked. If not provided, the word "on" is
5500 The optional fourth parameter (-label) is the user-readable label to
5501 be attached to the checkbox. If not provided, the checkbox name is
5506 The value of the checkbox can be retrieved using:
5508 $turned_on = $query->param('checkbox_name');
5510 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
5511 parameter. See checkbox_group() for further details.
5513 =head2 CREATING A RADIO BUTTON GROUP
5515 print $query->radio_group(-name=>'group_name',
5516 -values=>['eenie','meenie','minie'],
5523 print $query->radio_group('group_name',['eenie','meenie','minie'],
5524 'meenie','true',\%labels);
5527 HTML3-COMPATIBLE BROWSERS ONLY:
5529 print $query->radio_group(-name=>'group_name',
5530 -values=>['eenie','meenie','minie','moe'],
5531 -rows=2,-columns=>2);
5533 radio_group() creates a set of logically-related radio buttons
5534 (turning one member of the group on turns the others off)
5538 =item B<Parameters:>
5542 The first argument is the name of the group and is required (-name).
5546 The second argument (-values) is the list of values for the radio
5547 buttons. The values and the labels that appear on the page are
5548 identical. Pass an array I<reference> in the second argument, either
5549 using an anonymous array, as shown, or by referencing a named array as
5554 The optional third parameter (-default) is the name of the default
5555 button to turn on. If not specified, the first item will be the
5556 default. You can provide a nonexistent button name, such as "-" to
5557 start up with no buttons selected.
5561 The optional fourth parameter (-linebreak) can be set to 'true' to put
5562 line breaks between the buttons, creating a vertical list.
5566 The optional fifth parameter (-labels) is a pointer to an associative
5567 array relating the radio button values to user-visible labels to be
5568 used in the display. If not provided, the values themselves are
5573 B<HTML3-compatible browsers> (such as Netscape) can take advantage
5575 parameters B<-rows>, and B<-columns>. These parameters cause
5576 radio_group() to return an HTML3 compatible table containing
5577 the radio group formatted with the specified number of rows
5578 and columns. You can provide just the -columns parameter if you
5579 wish; radio_group will calculate the correct number of rows
5582 To include row and column headings in the returned table, you
5583 can use the B<-rowheader> and B<-colheader> parameters. Both
5584 of these accept a pointer to an array of headings to use.
5585 The headings are just decorative. They don't reorganize the
5586 interpretation of the radio buttons -- they're still a single named
5591 When the form is processed, the selected radio button can
5594 $which_radio_button = $query->param('group_name');
5596 The value returned by radio_group() is actually an array of button
5597 elements. You can capture them and use them within tables, lists,
5598 or in other creative ways:
5600 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
5601 &use_in_creative_way(@h);
5603 =head2 CREATING A SUBMIT BUTTON
5605 print $query->submit(-name=>'button_name',
5610 print $query->submit('button_name','value');
5612 submit() will create the query submission button. Every form
5613 should have one of these.
5617 =item B<Parameters:>
5621 The first argument (-name) is optional. You can give the button a
5622 name if you have several submission buttons in your form and you want
5623 to distinguish between them. The name will also be used as the
5624 user-visible label. Be aware that a few older browsers don't deal with this correctly and
5625 B<never> send back a value from a button.
5629 The second argument (-value) is also optional. This gives the button
5630 a value that will be passed to your script in the query string.
5634 You can figure out which button was pressed by using different
5635 values for each one:
5637 $which_one = $query->param('button_name');
5639 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
5640 parameter. See checkbox_group() for further details.
5642 =head2 CREATING A RESET BUTTON
5646 reset() creates the "reset" button. Note that it restores the
5647 form to its value from the last time the script was called,
5648 NOT necessarily to the defaults.
5650 Note that this conflicts with the Perl reset() built-in. Use
5651 CORE::reset() to get the original reset function.
5653 =head2 CREATING A DEFAULT BUTTON
5655 print $query->defaults('button_label')
5657 defaults() creates a button that, when invoked, will cause the
5658 form to be completely reset to its defaults, wiping out all the
5659 changes the user ever made.
5661 =head2 CREATING A HIDDEN FIELD
5663 print $query->hidden(-name=>'hidden_name',
5664 -default=>['value1','value2'...]);
5668 print $query->hidden('hidden_name','value1','value2'...);
5670 hidden() produces a text field that can't be seen by the user. It
5671 is useful for passing state variable information from one invocation
5672 of the script to the next.
5676 =item B<Parameters:>
5680 The first argument is required and specifies the name of this
5685 The second argument is also required and specifies its value
5686 (-default). In the named parameter style of calling, you can provide
5687 a single value here or a reference to a whole list
5691 Fetch the value of a hidden field this way:
5693 $hidden_value = $query->param('hidden_name');
5695 Note, that just like all the other form elements, the value of a
5696 hidden field is "sticky". If you want to replace a hidden field with
5697 some other values after the script has been called once you'll have to
5700 $query->param('hidden_name','new','values','here');
5702 =head2 CREATING A CLICKABLE IMAGE BUTTON
5704 print $query->image_button(-name=>'button_name',
5705 -src=>'/source/URL',
5710 print $query->image_button('button_name','/source/URL','MIDDLE');
5712 image_button() produces a clickable image. When it's clicked on the
5713 position of the click is returned to your script as "button_name.x"
5714 and "button_name.y", where "button_name" is the name you've assigned
5717 JAVASCRIPTING: image_button() recognizes the B<-onClick>
5718 parameter. See checkbox_group() for further details.
5722 =item B<Parameters:>
5726 The first argument (-name) is required and specifies the name of this
5731 The second argument (-src) is also required and specifies the URL
5735 The third option (-align, optional) is an alignment type, and may be
5736 TOP, BOTTOM or MIDDLE
5740 Fetch the value of the button this way:
5741 $x = $query->param('button_name.x');
5742 $y = $query->param('button_name.y');
5744 =head2 CREATING A JAVASCRIPT ACTION BUTTON
5746 print $query->button(-name=>'button_name',
5747 -value=>'user visible label',
5748 -onClick=>"do_something()");
5752 print $query->button('button_name',"do_something()");
5754 button() produces a button that is compatible with Netscape 2.0's
5755 JavaScript. When it's pressed the fragment of JavaScript code
5756 pointed to by the B<-onClick> parameter will be executed. On
5757 non-Netscape browsers this form element will probably not even
5762 Netscape browsers versions 1.1 and higher, and all versions of
5763 Internet Explorer, support a so-called "cookie" designed to help
5764 maintain state within a browser session. CGI.pm has several methods
5765 that support cookies.
5767 A cookie is a name=value pair much like the named parameters in a CGI
5768 query string. CGI scripts create one or more cookies and send
5769 them to the browser in the HTTP header. The browser maintains a list
5770 of cookies that belong to a particular Web server, and returns them
5771 to the CGI script during subsequent interactions.
5773 In addition to the required name=value pair, each cookie has several
5774 optional attributes:
5778 =item 1. an expiration time
5780 This is a time/date string (in a special GMT format) that indicates
5781 when a cookie expires. The cookie will be saved and returned to your
5782 script until this expiration date is reached if the user exits
5783 the browser and restarts it. If an expiration date isn't specified, the cookie
5784 will remain active until the user quits the browser.
5788 This is a partial or complete domain name for which the cookie is
5789 valid. The browser will return the cookie to any host that matches
5790 the partial domain name. For example, if you specify a domain name
5791 of ".capricorn.com", then the browser will return the cookie to
5792 Web servers running on any of the machines "www.capricorn.com",
5793 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
5794 must contain at least two periods to prevent attempts to match
5795 on top level domains like ".edu". If no domain is specified, then
5796 the browser will only return the cookie to servers on the host the
5797 cookie originated from.
5801 If you provide a cookie path attribute, the browser will check it
5802 against your script's URL before returning the cookie. For example,
5803 if you specify the path "/cgi-bin", then the cookie will be returned
5804 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
5805 and "/cgi-bin/customer_service/complain.pl", but not to the script
5806 "/cgi-private/site_admin.pl". By default, path is set to "/", which
5807 causes the cookie to be sent to any CGI script on your site.
5809 =item 4. a "secure" flag
5811 If the "secure" attribute is set, the cookie will only be sent to your
5812 script if the CGI request is occurring on a secure channel, such as SSL.
5816 The interface to HTTP cookies is the B<cookie()> method:
5818 $cookie = $query->cookie(-name=>'sessionID',
5821 -path=>'/cgi-bin/database',
5822 -domain=>'.capricorn.org',
5824 print $query->header(-cookie=>$cookie);
5826 B<cookie()> creates a new cookie. Its parameters include:
5832 The name of the cookie (required). This can be any string at all.
5833 Although browsers limit their cookie names to non-whitespace
5834 alphanumeric characters, CGI.pm removes this restriction by escaping
5835 and unescaping cookies behind the scenes.
5839 The value of the cookie. This can be any scalar value,
5840 array reference, or even associative array reference. For example,
5841 you can store an entire associative array into a cookie this way:
5843 $cookie=$query->cookie(-name=>'family information',
5844 -value=>\%childrens_ages);
5848 The optional partial path for which this cookie will be valid, as described
5853 The optional partial domain for which this cookie will be valid, as described
5858 The optional expiration date for this cookie. The format is as described
5859 in the section on the B<header()> method:
5861 "+1h" one hour from now
5865 If set to true, this cookie will only be used within a secure
5870 The cookie created by cookie() must be incorporated into the HTTP
5871 header within the string returned by the header() method:
5873 print $query->header(-cookie=>$my_cookie);
5875 To create multiple cookies, give header() an array reference:
5877 $cookie1 = $query->cookie(-name=>'riddle_name',
5878 -value=>"The Sphynx's Question");
5879 $cookie2 = $query->cookie(-name=>'answers',
5881 print $query->header(-cookie=>[$cookie1,$cookie2]);
5883 To retrieve a cookie, request it by name by calling cookie() method
5884 without the B<-value> parameter:
5888 $riddle = $query->cookie('riddle_name');
5889 %answers = $query->cookie('answers');
5891 Cookies created with a single scalar value, such as the "riddle_name"
5892 cookie, will be returned in that form. Cookies with array and hash
5893 values can also be retrieved.
5895 The cookie and CGI namespaces are separate. If you have a parameter
5896 named 'answers' and a cookie named 'answers', the values retrieved by
5897 param() and cookie() are independent of each other. However, it's
5898 simple to turn a CGI parameter into a cookie, and vice-versa:
5900 # turn a CGI parameter into a cookie
5901 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
5903 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
5905 See the B<cookie.cgi> example script for some ideas on how to use
5906 cookies effectively.
5908 =head1 WORKING WITH FRAMES
5910 It's possible for CGI.pm scripts to write into several browser panels
5911 and windows using the HTML 4 frame mechanism. There are three
5912 techniques for defining new frames programmatically:
5916 =item 1. Create a <Frameset> document
5918 After writing out the HTTP header, instead of creating a standard
5919 HTML document using the start_html() call, create a <FRAMESET>
5920 document that defines the frames on the page. Specify your script(s)
5921 (with appropriate parameters) as the SRC for each of the frames.
5923 There is no specific support for creating <FRAMESET> sections
5924 in CGI.pm, but the HTML is very simple to write. See the frame
5925 documentation in Netscape's home pages for details
5927 http://home.netscape.com/assist/net_sites/frames.html
5929 =item 2. Specify the destination for the document in the HTTP header
5931 You may provide a B<-target> parameter to the header() method:
5933 print $q->header(-target=>'ResultsWindow');
5935 This will tell the browser to load the output of your script into the
5936 frame named "ResultsWindow". If a frame of that name doesn't already
5937 exist, the browser will pop up a new window and load your script's
5938 document into that. There are a number of magic names that you can
5939 use for targets. See the frame documents on Netscape's home pages for
5942 =item 3. Specify the destination for the document in the <FORM> tag
5944 You can specify the frame to load in the FORM tag itself. With
5945 CGI.pm it looks like this:
5947 print $q->start_form(-target=>'ResultsWindow');
5949 When your script is reinvoked by the form, its output will be loaded
5950 into the frame named "ResultsWindow". If one doesn't already exist
5951 a new window will be created.
5955 The script "frameset.cgi" in the examples directory shows one way to
5956 create pages in which the fill-out form and the response live in
5957 side-by-side frames.
5959 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
5961 CGI.pm has limited support for HTML3's cascading style sheets (css).
5962 To incorporate a stylesheet into your document, pass the
5963 start_html() method a B<-style> parameter. The value of this
5964 parameter may be a scalar, in which case it is incorporated directly
5965 into a <STYLE> section, or it may be a hash reference. In the latter
5966 case you should provide the hash with one or more of B<-src> or
5967 B<-code>. B<-src> points to a URL where an externally-defined
5968 stylesheet can be found. B<-code> points to a scalar value to be
5969 incorporated into a <STYLE> section. Style definitions in B<-code>
5970 override similarly-named ones in B<-src>, hence the name "cascading."
5972 You may also specify the type of the stylesheet by adding the optional
5973 B<-type> parameter to the hash pointed to by B<-style>. If not
5974 specified, the style defaults to 'text/css'.
5976 To refer to a style within the body of your document, add the
5977 B<-class> parameter to any HTML element:
5979 print h1({-class=>'Fancy'},'Welcome to the Party');
5981 Or define styles on the fly with the B<-style> parameter:
5983 print h1({-style=>'Color: red;'},'Welcome to Hell');
5985 You may also use the new B<span()> element to apply a style to a
5988 print span({-style=>'Color: red;'},
5989 h1('Welcome to Hell'),
5990 "Where did that handbasket get to?"
5993 Note that you must import the ":html3" definitions to have the
5994 B<span()> method available. Here's a quick and dirty example of using
5995 CSS's. See the CSS specification at
5996 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
5998 use CGI qw/:standard :html3/;
6000 #here's a stylesheet incorporated directly into the page
6010 font-family: sans-serif;
6016 print start_html( -title=>'CGI with Style',
6017 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
6020 print h1('CGI with Style'),
6022 "Better read the cascading style sheet spec before playing with this!"),
6023 span({-style=>'color: magenta'},
6024 "Look Mom, no hands!",
6030 Pass an array reference to B<-style> in order to incorporate multiple
6031 stylesheets into your document.
6035 If you are running the script from the command line or in the perl
6036 debugger, you can pass the script a list of keywords or
6037 parameter=value pairs on the command line or from standard input (you
6038 don't have to worry about tricking your script into reading from
6039 environment variables). You can pass keywords like this:
6041 your_script.pl keyword1 keyword2 keyword3
6045 your_script.pl keyword1+keyword2+keyword3
6049 your_script.pl name1=value1 name2=value2
6053 your_script.pl name1=value1&name2=value2
6055 To turn off this feature, use the -no_debug pragma.
6057 To test the POST method, you may enable full debugging with the -debug
6058 pragma. This will allow you to feed newline-delimited name=value
6059 pairs to the script on standard input.
6061 When debugging, you can use quotes and backslashes to escape
6062 characters in the familiar shell manner, letting you place
6063 spaces and other funny characters in your parameter=value
6066 your_script.pl "name1='I am a long value'" "name2=two\ words"
6068 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
6070 The Dump() method produces a string consisting of all the query's
6071 name/value pairs formatted nicely as a nested list. This is useful
6072 for debugging purposes:
6077 Produces something that looks like:
6091 As a shortcut, you can interpolate the entire CGI object into a string
6092 and it will be replaced with the a nice HTML dump shown above:
6095 print "<H2>Current Values</H2> $query\n";
6097 =head1 FETCHING ENVIRONMENT VARIABLES
6099 Some of the more useful environment variables can be fetched
6100 through this interface. The methods are as follows:
6106 Return a list of MIME types that the remote browser accepts. If you
6107 give this method a single argument corresponding to a MIME type, as in
6108 $query->Accept('text/html'), it will return a floating point value
6109 corresponding to the browser's preference for this type from 0.0
6110 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
6111 list are handled correctly.
6113 Note that the capitalization changed between version 2.43 and 2.44 in
6114 order to avoid conflict with Perl's accept() function.
6116 =item B<raw_cookie()>
6118 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
6119 Netscape browsers version 1.1 and higher, and all versions of Internet
6120 Explorer. Cookies have a special format, and this method call just
6121 returns the raw form (?cookie dough). See cookie() for ways of
6122 setting and retrieving cooked cookies.
6124 Called with no parameters, raw_cookie() returns the packed cookie
6125 structure. You can separate it into individual cookies by splitting
6126 on the character sequence "; ". Called with the name of a cookie,
6127 retrieves the B<unescaped> form of the cookie. You can use the
6128 regular cookie() method to get the names, or use the raw_fetch()
6129 method from the CGI::Cookie module.
6131 =item B<user_agent()>
6133 Returns the HTTP_USER_AGENT variable. If you give
6134 this method a single argument, it will attempt to
6135 pattern match on it, allowing you to do something
6136 like $query->user_agent(netscape);
6138 =item B<path_info()>
6140 Returns additional path information from the script URL.
6141 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
6142 $query->path_info() returning "/additional/stuff".
6144 NOTE: The Microsoft Internet Information Server
6145 is broken with respect to additional path information. If
6146 you use the Perl DLL library, the IIS server will attempt to
6147 execute the additional path information as a Perl script.
6148 If you use the ordinary file associations mapping, the
6149 path information will be present in the environment,
6150 but incorrect. The best thing to do is to avoid using additional
6151 path information in CGI scripts destined for use with IIS.
6153 =item B<path_translated()>
6155 As per path_info() but returns the additional
6156 path information translated into a physical path, e.g.
6157 "/usr/local/etc/httpd/htdocs/additional/stuff".
6159 The Microsoft IIS is broken with respect to the translated
6162 =item B<remote_host()>
6164 Returns either the remote host name or IP address.
6165 if the former is unavailable.
6167 =item B<script_name()>
6169 Return the script name as a partial URL, for self-refering
6174 Return the URL of the page the browser was viewing
6175 prior to fetching your script. Not available for all
6178 =item B<auth_type ()>
6180 Return the authorization/verification method in use for this
6183 =item B<server_name ()>
6185 Returns the name of the server, usually the machine's host
6188 =item B<virtual_host ()>
6190 When using virtual hosts, returns the name of the host that
6191 the browser attempted to contact
6193 =item B<server_port ()>
6195 Return the port that the server is listening on.
6197 =item B<server_software ()>
6199 Returns the server software and version number.
6201 =item B<remote_user ()>
6203 Return the authorization/verification name used for user
6204 verification, if this script is protected.
6206 =item B<user_name ()>
6208 Attempt to obtain the remote user's name, using a variety of different
6209 techniques. This only works with older browsers such as Mosaic.
6210 Newer browsers do not report the user name for privacy reasons!
6212 =item B<request_method()>
6214 Returns the method used to access your script, usually
6215 one of 'POST', 'GET' or 'HEAD'.
6217 =item B<content_type()>
6219 Returns the content_type of data submitted in a POST, generally
6220 multipart/form-data or application/x-www-form-urlencoded
6224 Called with no arguments returns the list of HTTP environment
6225 variables, including such things as HTTP_USER_AGENT,
6226 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6227 like-named HTTP header fields in the request. Called with the name of
6228 an HTTP header field, returns its value. Capitalization and the use
6229 of hyphens versus underscores are not significant.
6231 For example, all three of these examples are equivalent:
6233 $requested_language = $q->http('Accept-language');
6234 $requested_language = $q->http('Accept_language');
6235 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6239 The same as I<http()>, but operates on the HTTPS environment variables
6240 present when the SSL protocol is in effect. Can be used to determine
6241 whether SSL is turned on.
6245 =head1 USING NPH SCRIPTS
6247 NPH, or "no-parsed-header", scripts bypass the server completely by
6248 sending the complete HTTP header directly to the browser. This has
6249 slight performance benefits, but is of most use for taking advantage
6250 of HTTP extensions that are not directly supported by your server,
6251 such as server push and PICS headers.
6253 Servers use a variety of conventions for designating CGI scripts as
6254 NPH. Many Unix servers look at the beginning of the script's name for
6255 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
6256 Internet Information Server, in contrast, try to decide whether a
6257 program is an NPH script by examining the first line of script output.
6260 CGI.pm supports NPH scripts with a special NPH mode. When in this
6261 mode, CGI.pm will output the necessary extra header information when
6262 the header() and redirect() methods are
6265 The Microsoft Internet Information Server requires NPH mode. As of
6266 version 2.30, CGI.pm will automatically detect when the script is
6267 running under IIS and put itself into this mode. You do not need to
6268 do this manually, although it won't hurt anything if you do. However,
6269 note that if you have applied Service Pack 6, much of the
6270 functionality of NPH scripts, including the ability to redirect while
6271 setting a cookie, b<do not work at all> on IIS without a special patch
6273 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
6274 Non-Parsed Headers Stripped From CGI Applications That Have nph-
6279 =item In the B<use> statement
6281 Simply add the "-nph" pragmato the list of symbols to be imported into
6284 use CGI qw(:standard -nph)
6286 =item By calling the B<nph()> method:
6288 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
6292 =item By using B<-nph> parameters
6294 in the B<header()> and B<redirect()> statements:
6296 print $q->header(-nph=>1);
6302 CGI.pm provides four simple functions for producing multipart
6303 documents of the type needed to implement server push. These
6304 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
6305 import these into your namespace, you must import the ":push" set.
6306 You are also advised to put the script into NPH mode and to set $| to
6307 1 to avoid buffering problems.
6309 Here is a simple script that demonstrates server push:
6311 #!/usr/local/bin/perl
6312 use CGI qw/:push -nph/;
6314 print multipart_init(-boundary=>'----here we go!');
6316 print multipart_start(-type=>'text/plain'),
6317 "The current time is ",scalar(localtime),"\n";
6319 print multipart_end;
6321 print multipart_final;
6326 This script initializes server push by calling B<multipart_init()>.
6327 It then enters a loop in which it begins a new multipart section by
6328 calling B<multipart_start()>, prints the current local time,
6329 and ends a multipart section with B<multipart_end()>. It then sleeps
6330 a second, and begins again. On the final iteration, it ends the
6331 multipart section with B<multipart_final()> rather than with
6336 =item multipart_init()
6338 multipart_init(-boundary=>$boundary);
6340 Initialize the multipart system. The -boundary argument specifies
6341 what MIME boundary string to use to separate parts of the document.
6342 If not provided, CGI.pm chooses a reasonable boundary for you.
6344 =item multipart_start()
6346 multipart_start(-type=>$type)
6348 Start a new part of the multipart document using the specified MIME
6349 type. If not specified, text/html is assumed.
6351 =item multipart_end()
6355 End a part. You must remember to call multipart_end() once for each
6356 multipart_start(), except at the end of the last part of the multipart
6357 document when multipart_final() should be called instead of multipart_end().
6359 =item multipart_final()
6363 End all parts. You should call multipart_final() rather than
6364 multipart_end() at the end of the last part of the multipart document.
6368 Users interested in server push applications should also have a look
6369 at the CGI::Push module.
6371 Only Netscape Navigator supports server push. Internet Explorer
6374 =head1 Avoiding Denial of Service Attacks
6376 A potential problem with CGI.pm is that, by default, it attempts to
6377 process form POSTings no matter how large they are. A wily hacker
6378 could attack your site by sending a CGI script a huge POST of many
6379 megabytes. CGI.pm will attempt to read the entire POST into a
6380 variable, growing hugely in size until it runs out of memory. While
6381 the script attempts to allocate the memory the system may slow down
6382 dramatically. This is a form of denial of service attack.
6384 Another possible attack is for the remote user to force CGI.pm to
6385 accept a huge file upload. CGI.pm will accept the upload and store it
6386 in a temporary directory even if your script doesn't expect to receive
6387 an uploaded file. CGI.pm will delete the file automatically when it
6388 terminates, but in the meantime the remote user may have filled up the
6389 server's disk space, causing problems for other programs.
6391 The best way to avoid denial of service attacks is to limit the amount
6392 of memory, CPU time and disk space that CGI scripts can use. Some Web
6393 servers come with built-in facilities to accomplish this. In other
6394 cases, you can use the shell I<limit> or I<ulimit>
6395 commands to put ceilings on CGI resource usage.
6398 CGI.pm also has some simple built-in protections against denial of
6399 service attacks, but you must activate them before you can use them.
6400 These take the form of two global variables in the CGI name space:
6404 =item B<$CGI::POST_MAX>
6406 If set to a non-negative integer, this variable puts a ceiling
6407 on the size of POSTings, in bytes. If CGI.pm detects a POST
6408 that is greater than the ceiling, it will immediately exit with an error
6409 message. This value will affect both ordinary POSTs and
6410 multipart POSTs, meaning that it limits the maximum size of file
6411 uploads as well. You should set this to a reasonably high
6412 value, such as 1 megabyte.
6414 =item B<$CGI::DISABLE_UPLOADS>
6416 If set to a non-zero value, this will disable file uploads
6417 completely. Other fill-out form values will work as usual.
6421 You can use these variables in either of two ways.
6425 =item B<1. On a script-by-script basis>
6427 Set the variable at the top of the script, right after the "use" statement:
6429 use CGI qw/:standard/;
6430 use CGI::Carp 'fatalsToBrowser';
6431 $CGI::POST_MAX=1024 * 100; # max 100K posts
6432 $CGI::DISABLE_UPLOADS = 1; # no uploads
6434 =item B<2. Globally for all scripts>
6436 Open up CGI.pm, find the definitions for $POST_MAX and
6437 $DISABLE_UPLOADS, and set them to the desired values. You'll
6438 find them towards the top of the file in a subroutine named
6439 initialize_globals().
6443 An attempt to send a POST larger than $POST_MAX bytes will cause
6444 I<param()> to return an empty CGI parameter list. You can test for
6445 this event by checking I<cgi_error()>, either after you create the CGI
6446 object or, if you are using the function-oriented interface, call
6447 <param()> for the first time. If the POST was intercepted, then
6448 cgi_error() will return the message "413 POST too large".
6450 This error message is actually defined by the HTTP protocol, and is
6451 designed to be returned to the browser as the CGI script's status
6454 $uploaded_file = param('upload');
6455 if (!$uploaded_file && cgi_error()) {
6456 print header(-status=>cgi_error());
6460 However it isn't clear that any browser currently knows what to do
6461 with this status code. It might be better just to create an
6462 HTML page that warns the user of the problem.
6464 =head1 COMPATIBILITY WITH CGI-LIB.PL
6466 To make it easier to port existing programs that use cgi-lib.pl the
6467 compatibility routine "ReadParse" is provided. Porting is simple:
6470 require "cgi-lib.pl";
6472 print "The value of the antique is $in{antique}.\n";
6477 print "The value of the antique is $in{antique}.\n";
6479 CGI.pm's ReadParse() routine creates a tied variable named %in,
6480 which can be accessed to obtain the query variables. Like
6481 ReadParse, you can also provide your own variable. Infrequently
6482 used features of ReadParse, such as the creation of @in and $in
6483 variables, are not supported.
6485 Once you use ReadParse, you can retrieve the query object itself
6489 print $q->textfield(-name=>'wow',
6490 -value=>'does this really work?');
6492 This allows you to start using the more interesting features
6493 of CGI.pm without rewriting your old scripts from scratch.
6495 =head1 AUTHOR INFORMATION
6497 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
6499 This library is free software; you can redistribute it and/or modify
6500 it under the same terms as Perl itself.
6502 Address bug reports and comments to: lstein@cshl.org. When sending
6503 bug reports, please provide the version of CGI.pm, the version of
6504 Perl, the name and version of your Web server, and the name and
6505 version of the operating system you are using. If the problem is even
6506 remotely browser dependent, please provide information about the
6507 affected browers as well.
6511 Thanks very much to:
6515 =item Matt Heffron (heffron@falstaff.css.beckman.com)
6517 =item James Taylor (james.taylor@srs.gov)
6519 =item Scott Anguish <sanguish@digifix.com>
6521 =item Mike Jewell (mlj3u@virginia.edu)
6523 =item Timothy Shimmin (tes@kbs.citri.edu.au)
6525 =item Joergen Haegg (jh@axis.se)
6527 =item Laurent Delfosse (delfosse@delfosse.com)
6529 =item Richard Resnick (applepi1@aol.com)
6531 =item Craig Bishop (csb@barwonwater.vic.gov.au)
6533 =item Tony Curtis (tc@vcpc.univie.ac.at)
6535 =item Tim Bunce (Tim.Bunce@ig.co.uk)
6537 =item Tom Christiansen (tchrist@convex.com)
6539 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
6541 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
6543 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
6545 =item Stephen Dahmen (joyfire@inxpress.net)
6547 =item Ed Jordan (ed@fidalgo.net)
6549 =item David Alan Pisoni (david@cnation.com)
6551 =item Doug MacEachern (dougm@opengroup.org)
6553 =item Robin Houston (robin@oneworld.org)
6555 =item ...and many many more...
6557 for suggestions and bug fixes.
6561 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
6564 #!/usr/local/bin/perl
6570 print $query->header;
6571 print $query->start_html("Example CGI.pm Form");
6572 print "<H1> Example CGI.pm Form</H1>\n";
6573 &print_prompt($query);
6576 print $query->end_html;
6581 print $query->start_form;
6582 print "<EM>What's your name?</EM><BR>";
6583 print $query->textfield('name');
6584 print $query->checkbox('Not my real name');
6586 print "<P><EM>Where can you find English Sparrows?</EM><BR>";
6587 print $query->checkbox_group(
6588 -name=>'Sparrow locations',
6589 -values=>[England,France,Spain,Asia,Hoboken],
6591 -defaults=>[England,Asia]);
6593 print "<P><EM>How far can they fly?</EM><BR>",
6594 $query->radio_group(
6596 -values=>['10 ft','1 mile','10 miles','real far'],
6597 -default=>'1 mile');
6599 print "<P><EM>What's your favorite color?</EM> ";
6600 print $query->popup_menu(-name=>'Color',
6601 -values=>['black','brown','red','yellow'],
6604 print $query->hidden('Reference','Monty Python and the Holy Grail');
6606 print "<P><EM>What have you got there?</EM><BR>";
6607 print $query->scrolling_list(
6608 -name=>'possessions',
6609 -values=>['A Coconut','A Grail','An Icon',
6610 'A Sword','A Ticket'],
6614 print "<P><EM>Any parting comments?</EM><BR>";
6615 print $query->textarea(-name=>'Comments',
6619 print "<P>",$query->reset;
6620 print $query->submit('Action','Shout');
6621 print $query->submit('Action','Scream');
6622 print $query->endform;
6630 print "<H2>Here are the current settings in this form</H2>";
6632 foreach $key ($query->param) {
6633 print "<STRONG>$key</STRONG> -> ";
6634 @values = $query->param($key);
6635 print join(", ",@values),"<BR>\n";
6642 <ADDRESS>Lincoln D. Stein</ADDRESS><BR>
6643 <A HREF="/">Home Page</A>
6649 This module has grown large and monolithic. Furthermore it's doing many
6650 things, such as handling URLs, parsing CGI input, writing HTML, etc., that
6651 are also done in the LWP modules. It should be discarded in favor of
6652 the CGI::* modules, but somehow I continue to work on it.
6654 Note that the code is truly contorted in order to avoid spurious
6655 warnings when programs are run with the B<-w> switch.
6659 L<CGI::Carp>, L<URI::URL>, L<CGI::Request>, L<CGI::MiniSvr>,
6660 L<CGI::Base>, L<CGI::Form>, L<CGI::Push>, L<CGI::Fast>,