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.200 2006/02/08 18:28:54 lstein Exp $';
22 $CGI::VERSION='3.16_01';
24 # HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.
25 # UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.
26 # $CGITempFile::TMPDIRECTORY = '/usr/tmp';
27 use CGI::Util qw(rearrange make_attributes unescape escape expires ebcdic2ascii ascii2ebcdic);
29 #use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30 # 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
32 use constant XHTML_DTD => ['-//W3C//DTD XHTML 1.0 Transitional//EN',
33 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'];
37 $TAINTED = substr("$0$^X",0,0);
40 $MOD_PERL = 0; # no mod_perl by default
43 # >>>>> Here are some globals that you might want to adjust <<<<<<
44 sub initialize_globals {
45 # Set this to 1 to enable copious autoloader debugging messages
48 # Set this to 1 to generate XTML-compatible output
51 # Change this to the preferred DTD to print in start_html()
52 # or use default_dtd('text of DTD to use');
53 $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
54 'http://www.w3.org/TR/html4/loose.dtd' ] ;
56 # Set this to 1 to enable NOSTICKY scripts
58 # 1) use CGI qw(-nosticky)
59 # 2) $CGI::nosticky(1)
62 # Set this to 1 to enable NPH scripts
66 # 3) print header(-nph=>1)
69 # Set this to 1 to enable debugging from @ARGV
70 # Set to 2 to enable debugging from STDIN
73 # Set this to 1 to make the temporary files created
74 # during file uploads safe from prying eyes
76 # 1) use CGI qw(:private_tempfiles)
77 # 2) CGI::private_tempfiles(1);
78 $PRIVATE_TEMPFILES = 0;
80 # Set this to 1 to generate automatic tab indexes
83 # Set this to 1 to cause files uploaded in multipart documents
84 # to be closed, instead of caching the file handle
86 # 1) use CGI qw(:close_upload_files)
87 # 2) $CGI::close_upload_files(1);
88 # Uploads with many files run out of file handles.
89 # Also, for performance, since the file is already on disk,
90 # it can just be renamed, instead of read and written.
91 $CLOSE_UPLOAD_FILES = 0;
93 # Set this to a positive value to limit the size of a POSTing
94 # to a certain number of bytes:
97 # Change this to 1 to disable uploads entirely:
100 # Automatically determined -- don't change
103 # Change this to 1 to suppress redundant HTTP headers
106 # separate the name=value pairs by semicolons rather than ampersands
107 $USE_PARAM_SEMICOLONS = 1;
109 # Do not include undefined params parsed from query string
110 # use CGI qw(-no_undef_params);
111 $NO_UNDEF_PARAMS = 0;
113 # Other globals that you shouldn't worry about.
116 $DTD_PUBLIC_IDENTIFIER = "";
119 undef $QUERY_CHARSET;
120 undef %QUERY_FIELDNAMES;
122 # prevent complaints by mod_perl
126 # ------------------ START OF THE LIBRARY ------------
128 *end_form = \&endform;
131 initialize_globals();
133 # FIGURE OUT THE OS WE'RE RUNNING UNDER
134 # Some systems support the $^O variable. If not
135 # available then require() the Config library
139 $OS = $Config::Config{'osname'};
142 if ($OS =~ /^MSWin/i) {
144 } elsif ($OS =~ /^VMS/i) {
146 } elsif ($OS =~ /^dos/i) {
148 } elsif ($OS =~ /^MacOS/i) {
150 } elsif ($OS =~ /^os2/i) {
152 } elsif ($OS =~ /^epoc/i) {
154 } elsif ($OS =~ /^cygwin/i) {
160 # Some OS logic. Binary mode enabled on DOS, NT and VMS
161 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin|CYGWIN)/;
163 # This is the default class for the CGI object to use when all else fails.
164 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
166 # This is where to look for autoloaded routines.
167 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
169 # The path separator is a slash, backslash or semicolon, depending
172 UNIX => '/', OS2 => '\\', EPOC => '/', CYGWIN => '/',
173 WINDOWS => '\\', DOS => '\\', MACINTOSH => ':', VMS => '/'
176 # This no longer seems to be necessary
177 # Turn on NPH scripts by default when running under IIS server!
178 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
179 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
181 # Turn on special checking for Doug MacEachern's modperl
182 if (exists $ENV{MOD_PERL}) {
183 # mod_perl handlers may run system() on scripts using CGI.pm;
184 # Make sure so we don't get fooled by inherited $ENV{MOD_PERL}
185 if (exists $ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) {
187 require Apache2::Response;
188 require Apache2::RequestRec;
189 require Apache2::RequestUtil;
190 require Apache2::RequestIO;
198 # Turn on special checking for ActiveState's PerlEx
199 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
201 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
202 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
203 # and sometimes CR). The most popular VMS web server
204 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
205 # use ASCII, so \015\012 means something different. I find this all
207 $EBCDIC = "\t" ne "\011";
216 if ($needs_binmode) {
217 $CGI::DefaultClass->binmode(\*main::STDOUT);
218 $CGI::DefaultClass->binmode(\*main::STDIN);
219 $CGI::DefaultClass->binmode(\*main::STDERR);
223 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
224 tt u i b blockquote pre img a address cite samp dfn html head
225 base body Link nextid title meta kbd start_html end_html
226 input Select option comment charset escapeHTML/],
227 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
228 embed basefont style span layer ilayer font frameset frame script small big Area Map/],
229 ':html4'=>[qw/abbr acronym bdo col colgroup del fieldset iframe
230 ins label legend noframes noscript object optgroup Q
232 ':netscape'=>[qw/blink fontsize center/],
233 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
234 submit reset defaults radio_group popup_menu button autoEscape
235 scrolling_list image_button start_form end_form startform endform
236 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
237 ':cgi'=>[qw/param upload path_info path_translated request_uri url self_url script_name
239 raw_cookie request_method query_string Accept user_agent remote_host content_type
240 remote_addr referer server_name server_software server_port server_protocol virtual_port
241 virtual_host remote_ident auth_type http append
242 save_parameters restore_parameters param_fetch
243 remote_user user_name header redirect import_names put
244 Delete Delete_all url_param cgi_error/],
245 ':ssl' => [qw/https/],
246 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
247 ':html' => [qw/:html2 :html3 :html4 :netscape/],
248 ':standard' => [qw/:html2 :html3 :html4 :form :cgi/],
249 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
250 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal :html4/]
253 # Custom 'can' method for both autoloaded and non-autoloaded subroutines.
254 # Author: Cees Hek <cees@sitesuite.com.au>
257 my($class, $method) = @_;
259 # See if UNIVERSAL::can finds it.
261 if (my $func = $class -> SUPER::can($method) ){
265 # Try to compile the function.
268 # _compile looks at $AUTOLOAD for the function name.
270 local $AUTOLOAD = join "::", $class, $method;
274 # Now that the function is loaded (if it exists)
275 # just use UNIVERSAL::can again to do the work.
277 return $class -> SUPER::can($method);
280 # to import symbols into caller
284 # This causes modules to clash.
288 $self->_setup_symbols(@_);
289 my ($callpack, $callfile, $callline) = caller;
291 # To allow overriding, search through the packages
292 # Till we find one in which the correct subroutine is defined.
293 my @packages = ($self,@{"$self\:\:ISA"});
294 foreach $sym (keys %EXPORT) {
296 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
297 foreach $pck (@packages) {
298 if (defined(&{"$pck\:\:$sym"})) {
303 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
309 $pack->_setup_symbols('-compile',@_);
314 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
316 return ($tag) unless $EXPORT_TAGS{$tag};
317 foreach (@{$EXPORT_TAGS{$tag}}) {
318 push(@r,&expand_tags($_));
324 # The new routine. This will check the current environment
325 # for an existing query string, and initialize itself, if so.
328 my($class,@initializer) = @_;
331 bless $self,ref $class || $class || $DefaultClass;
332 if (ref($initializer[0])
333 && (UNIVERSAL::isa($initializer[0],'Apache')
335 UNIVERSAL::isa($initializer[0],'Apache2::RequestRec')
337 $self->r(shift @initializer);
339 if (ref($initializer[0])
340 && (UNIVERSAL::isa($initializer[0],'CODE'))) {
341 $self->upload_hook(shift @initializer, shift @initializer);
344 if ($MOD_PERL == 1) {
345 $self->r(Apache->request) unless $self->r;
347 $r->register_cleanup(\&CGI::_reset_globals);
350 # XXX: once we have the new API
351 # will do a real PerlOptions -SetupEnv check
352 $self->r(Apache2::RequestUtil->request) unless $self->r;
354 $r->subprocess_env unless exists $ENV{REQUEST_METHOD};
355 $r->pool->cleanup_register(\&CGI::_reset_globals);
359 $self->_reset_globals if $PERLEX;
360 $self->init(@initializer);
364 # We provide a DESTROY method so that we can ensure that
365 # temporary files are closed (via Fh->DESTROY) before they
366 # are unlinked (via CGITempFile->DESTROY) because it is not
367 # possible to unlink an open file on Win32. We explicitly
368 # call DESTROY on each, rather than just undefing them and
369 # letting Perl DESTROY them by garbage collection, in case the
370 # user is still holding any reference to them as well.
373 if ($OS eq 'WINDOWS') {
374 foreach my $href (values %{$self->{'.tmpfiles'}}) {
375 $href->{hndl}->DESTROY if defined $href->{hndl};
376 $href->{name}->DESTROY if defined $href->{name};
383 my $r = $self->{'.r'};
384 $self->{'.r'} = shift if @_;
390 if (ref $_[0] eq 'CODE') {
391 $CGI::Q = $self = $CGI::DefaultClass->new(@_);
395 my ($hook,$data) = @_;
396 $self->{'.upload_hook'} = $hook;
397 $self->{'.upload_data'} = $data;
401 # Returns the value(s)of a named parameter.
402 # If invoked in a list context, returns the
403 # entire list. Otherwise returns the first
404 # member of the list.
405 # If name is not provided, return a list of all
406 # the known parameters names available.
407 # If more than one argument is provided, the
408 # second and subsequent arguments are used to
409 # set the value of the parameter.
412 my($self,@p) = self_or_default(@_);
413 return $self->all_parameters unless @p;
414 my($name,$value,@other);
416 # For compatibility between old calling style and use_named_parameters() style,
417 # we have to special case for a single parameter present.
419 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
422 if (substr($p[0],0,1) eq '-') {
423 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
425 foreach ($value,@other) {
426 push(@values,$_) if defined($_);
429 # If values is provided, then we set it.
431 $self->add_parameter($name);
432 $self->{$name}=[@values];
438 return unless defined($name) && $self->{$name};
439 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
442 sub self_or_default {
443 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
444 unless (defined($_[0]) &&
445 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
447 $Q = $CGI::DefaultClass->new unless defined($Q);
450 return wantarray ? @_ : $Q;
454 local $^W=0; # prevent a warning
455 if (defined($_[0]) &&
456 (substr(ref($_[0]),0,3) eq 'CGI'
457 || UNIVERSAL::isa($_[0],'CGI'))) {
460 return ($DefaultClass,@_);
464 ########################################
465 # THESE METHODS ARE MORE OR LESS PRIVATE
466 # GO TO THE __DATA__ SECTION TO SEE MORE
468 ########################################
470 # Initialize the query object from the environment.
471 # If a parameter list is found, this object will be set
472 # to an associative array in which parameter names are keys
473 # and the values are stored as lists
474 # If a keyword list is found, this method creates a bogus
475 # parameter list with the single parameter 'keywords'.
479 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
481 my $initializer = shift; # for backward compatibility
484 # set autoescaping on by default
485 $self->{'escape'} = 1;
487 # if we get called more than once, we want to initialize
488 # ourselves from the original query (which may be gone
489 # if it was read from STDIN originally.)
490 if (defined(@QUERY_PARAM) && !defined($initializer)) {
491 foreach (@QUERY_PARAM) {
492 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
494 $self->charset($QUERY_CHARSET);
495 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
499 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
500 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
502 $fh = to_filehandle($initializer) if $initializer;
504 # set charset to the safe ISO-8859-1
505 $self->charset('ISO-8859-1');
509 # avoid unreasonably large postings
510 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
511 # quietly read and discard the post
513 my $tmplength = $content_length;
514 while($tmplength > 0) {
515 my $maxbuffer = ($tmplength < 10000)?$tmplength:10000;
516 my $bytesread = $MOD_PERL ? $self->r->read($buffer,$maxbuffer) : read(STDIN,$buffer,$maxbuffer);
517 $tmplength -= $bytesread;
519 $self->cgi_error("413 Request entity too large");
523 # Process multipart postings, but only if the initializer is
526 && defined($ENV{'CONTENT_TYPE'})
527 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
528 && !defined($initializer)
530 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
531 $self->read_multipart($boundary,$content_length);
535 # If initializer is defined, then read parameters
537 if (defined($initializer)) {
538 if (UNIVERSAL::isa($initializer,'CGI')) {
539 $query_string = $initializer->query_string;
542 if (ref($initializer) && ref($initializer) eq 'HASH') {
543 foreach (keys %$initializer) {
544 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
549 if (defined($fh) && ($fh ne '')) {
555 # massage back into standard format
556 if ("@lines" =~ /=/) {
557 $query_string=join("&",@lines);
559 $query_string=join("+",@lines);
564 if (defined($fh) && ($fh ne '')) {
570 # massage back into standard format
571 if ("@lines" =~ /=/) {
572 $query_string=join("&",@lines);
574 $query_string=join("+",@lines);
579 # last chance -- treat it as a string
580 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
581 $query_string = $initializer;
586 # If method is GET or HEAD, fetch the query from
588 if ($meth=~/^(GET|HEAD)$/) {
590 $query_string = $self->r->args;
592 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
593 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
598 if ($meth eq 'POST') {
599 $self->read_from_client(\$query_string,$content_length,0)
600 if $content_length > 0;
601 # Some people want to have their cake and eat it too!
602 # Uncomment this line to have the contents of the query string
603 # APPENDED to the POST data.
604 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
608 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
609 # Check the command line and then the standard input for data.
610 # We use the shellwords package in order to behave the way that
611 # UN*X programmers expect.
614 my $cmdline_ret = read_from_cmdline();
615 $query_string = $cmdline_ret->{'query_string'};
616 if (defined($cmdline_ret->{'subpath'}))
618 $self->path_info($cmdline_ret->{'subpath'});
623 # YL: Begin Change for XML handler 10/19/2001
625 && defined($ENV{'CONTENT_TYPE'})
626 && $ENV{'CONTENT_TYPE'} !~ m|^application/x-www-form-urlencoded|
627 && $ENV{'CONTENT_TYPE'} !~ m|^multipart/form-data| ) {
628 my($param) = 'POSTDATA' ;
629 $self->add_parameter($param) ;
630 push (@{$self->{$param}},$query_string);
631 undef $query_string ;
633 # YL: End Change for XML handler 10/19/2001
635 # We now have the query string in hand. We do slightly
636 # different things for keyword lists and parameter lists.
637 if (defined $query_string && length $query_string) {
638 if ($query_string =~ /[&=;]/) {
639 $self->parse_params($query_string);
641 $self->add_parameter('keywords');
642 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
646 # Special case. Erase everything if there is a field named
648 if ($self->param('.defaults')) {
652 # Associative array containing our defined fieldnames
653 $self->{'.fieldnames'} = {};
654 foreach ($self->param('.cgifields')) {
655 $self->{'.fieldnames'}->{$_}++;
658 # Clear out our default submission button flag if present
659 $self->delete('.submit');
660 $self->delete('.cgifields');
662 $self->save_request unless defined $initializer;
665 # FUNCTIONS TO OVERRIDE:
666 # Turn a string into a filehandle
669 return undef unless $thingy;
670 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
671 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
674 while (my $package = caller($caller++)) {
675 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
676 return $tmp if defined(fileno($tmp));
682 # send output to the browser
684 my($self,@p) = self_or_default(@_);
688 # print to standard output (for overriding in mod_perl)
694 # get/set last cgi_error
696 my ($self,$err) = self_or_default(@_);
697 $self->{'.cgi_error'} = $err if defined $err;
698 return $self->{'.cgi_error'};
703 # We're going to play with the package globals now so that if we get called
704 # again, we initialize ourselves in exactly the same way. This allows
705 # us to have several of these objects.
706 @QUERY_PARAM = $self->param; # save list of parameters
707 foreach (@QUERY_PARAM) {
708 next unless defined $_;
709 $QUERY_PARAM{$_}=$self->{$_};
711 $QUERY_CHARSET = $self->charset;
712 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
716 my($self,$tosplit) = @_;
717 my(@pairs) = split(/[&;]/,$tosplit);
720 ($param,$value) = split('=',$_,2);
721 next unless defined $param;
722 next if $NO_UNDEF_PARAMS and not defined $value;
723 $value = '' unless defined $value;
724 $param = unescape($param);
725 $value = unescape($value);
726 $self->add_parameter($param);
727 push (@{$self->{$param}},$value);
733 return unless defined $param;
734 push (@{$self->{'.parameters'}},$param)
735 unless defined($self->{$param});
740 return () unless defined($self) && $self->{'.parameters'};
741 return () unless @{$self->{'.parameters'}};
742 return @{$self->{'.parameters'}};
745 # put a filehandle into binary mode (DOS)
747 return unless defined($_[1]) && defined fileno($_[1]);
748 CORE::binmode($_[1]);
752 my ($self,$tagname) = @_;
755 my (\$q,\$a,\@rest) = self_or_default(\@_);
757 if (ref(\$a) && ref(\$a) eq 'HASH') {
758 my(\@attr) = make_attributes(\$a,\$q->{'escape'});
759 \$attr = " \@attr" if \@attr;
761 unshift \@rest,\$a if defined \$a;
764 if ($tagname=~/start_(\w+)/i) {
765 $func .= qq! return "<\L$1\E\$attr>";} !;
766 } elsif ($tagname=~/end_(\w+)/i) {
767 $func .= qq! return "<\L/$1\E>"; } !;
770 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@rest;
771 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
772 my \@result = map { "\$tag\$_\$untag" }
773 (ref(\$rest[0]) eq 'ARRAY') ? \@{\$rest[0]} : "\@rest";
781 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
782 my $func = &_compile;
787 my($func) = $AUTOLOAD;
788 my($pack,$func_name);
790 local($1,$2); # this fixes an obscure variable suicide problem.
791 $func=~/(.+)::([^:]+)$/;
792 ($pack,$func_name) = ($1,$2);
793 $pack=~s/::SUPER$//; # fix another obscure problem
794 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
795 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
797 my($sub) = \%{"$pack\:\:SUBS"};
799 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
801 eval "package $pack; $$auto";
802 croak("$AUTOLOAD: $@") if $@;
803 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
805 my($code) = $sub->{$func_name};
807 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
809 (my $base = $func_name) =~ s/^(start_|end_)//i;
810 if ($EXPORT{':any'} ||
813 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
814 && $EXPORT_OK{$base}) {
815 $code = $CGI::DefaultClass->_make_tag_func($func_name);
818 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
820 eval "package $pack; $code";
823 croak("$AUTOLOAD: $@");
826 CORE::delete($sub->{$func_name}); #free storage
827 return "$pack\:\:$func_name";
833 return '' unless $value;
834 return $XHTML ? qq(selected="selected" ) : qq(selected );
840 return '' unless $value;
841 return $XHTML ? qq(checked="checked" ) : qq(checked );
844 sub _reset_globals { initialize_globals(); }
850 # to avoid reexporting unwanted variables
854 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
855 $NPH++, next if /^[:-]nph$/;
856 $NOSTICKY++, next if /^[:-]nosticky$/;
857 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
858 $DEBUG=2, next if /^[:-][Dd]ebug$/;
859 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
860 $XHTML++, next if /^[:-]xhtml$/;
861 $XHTML=0, next if /^[:-]no_?xhtml$/;
862 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
863 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
864 $TABINDEX++, next if /^[:-]tabindex$/;
865 $CLOSE_UPLOAD_FILES++, next if /^[:-]close_upload_files$/;
866 $EXPORT{$_}++, next if /^[:-]any$/;
867 $compile++, next if /^[:-]compile$/;
868 $NO_UNDEF_PARAMS++, next if /^[:-]no_undef_params$/;
870 # This is probably extremely evil code -- to be deleted some day.
871 if (/^[-]autoload$/) {
872 my($pkg) = caller(1);
873 *{"${pkg}::AUTOLOAD"} = sub {
874 my($routine) = $AUTOLOAD;
875 $routine =~ s/^.*::/CGI::/;
881 foreach (&expand_tags($_)) {
882 tr/a-zA-Z0-9_//cd; # don't allow weird function names
886 _compile_all(keys %EXPORT) if $compile;
891 my ($self,$charset) = self_or_default(@_);
892 $self->{'.charset'} = $charset if defined $charset;
897 my ($self,$new_value) = self_or_default(@_);
898 $self->{'.elid'} = $new_value if defined $new_value;
899 sprintf('%010d',$self->{'.elid'}++);
903 my ($self,$new_value) = self_or_default(@_);
904 $self->{'.etab'} ||= 1;
905 $self->{'.etab'} = $new_value if defined $new_value;
906 my $tab = $self->{'.etab'}++;
907 return '' unless $TABINDEX or defined $new_value;
908 return qq(tabindex="$tab" );
911 ###############################################################################
912 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
913 ###############################################################################
914 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
915 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
919 'URL_ENCODED'=> <<'END_OF_FUNC',
920 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
923 'MULTIPART' => <<'END_OF_FUNC',
924 sub MULTIPART { 'multipart/form-data'; }
927 'SERVER_PUSH' => <<'END_OF_FUNC',
928 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
931 'new_MultipartBuffer' => <<'END_OF_FUNC',
932 # Create a new multipart buffer
933 sub new_MultipartBuffer {
934 my($self,$boundary,$length) = @_;
935 return MultipartBuffer->new($self,$boundary,$length);
939 'read_from_client' => <<'END_OF_FUNC',
940 # Read data from a file handle
941 sub read_from_client {
942 my($self, $buff, $len, $offset) = @_;
943 local $^W=0; # prevent a warning
945 ? $self->r->read($$buff, $len, $offset)
946 : read(\*STDIN, $$buff, $len, $offset);
950 'delete' => <<'END_OF_FUNC',
952 # Deletes the named parameter entirely.
955 my($self,@p) = self_or_default(@_);
956 my(@names) = rearrange([NAME],@p);
957 my @to_delete = ref($names[0]) eq 'ARRAY' ? @$names[0] : @names;
959 foreach my $name (@to_delete)
961 CORE::delete $self->{$name};
962 CORE::delete $self->{'.fieldnames'}->{$name};
965 @{$self->{'.parameters'}}=grep { !exists($to_delete{$_}) } $self->param();
970 #### Method: import_names
971 # Import all parameters into the given namespace.
972 # Assumes namespace 'Q' if not specified
974 'import_names' => <<'END_OF_FUNC',
976 my($self,$namespace,$delete) = self_or_default(@_);
977 $namespace = 'Q' unless defined($namespace);
978 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
979 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
980 # can anyone find an easier way to do this?
981 foreach (keys %{"${namespace}::"}) {
982 local *symbol = "${namespace}::${_}";
988 my($param,@value,$var);
989 foreach $param ($self->param) {
990 # protect against silly names
991 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
992 $var =~ s/^(?=\d)/_/;
993 local *symbol = "${namespace}::$var";
994 @value = $self->param($param);
1001 #### Method: keywords
1002 # Keywords acts a bit differently. Calling it in a list context
1003 # returns the list of keywords.
1004 # Calling it in a scalar context gives you the size of the list.
1006 'keywords' => <<'END_OF_FUNC',
1008 my($self,@values) = self_or_default(@_);
1009 # If values is provided, then we set it.
1010 $self->{'keywords'}=[@values] if @values;
1011 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
1016 # These are some tie() interfaces for compatibility
1017 # with Steve Brenner's cgi-lib.pl routines
1018 'Vars' => <<'END_OF_FUNC',
1023 return %in if wantarray;
1028 # These are some tie() interfaces for compatibility
1029 # with Steve Brenner's cgi-lib.pl routines
1030 'ReadParse' => <<'END_OF_FUNC',
1037 *in=*{"${pkg}::in"};
1040 return scalar(keys %in);
1044 'PrintHeader' => <<'END_OF_FUNC',
1046 my($self) = self_or_default(@_);
1047 return $self->header();
1051 'HtmlTop' => <<'END_OF_FUNC',
1053 my($self,@p) = self_or_default(@_);
1054 return $self->start_html(@p);
1058 'HtmlBot' => <<'END_OF_FUNC',
1060 my($self,@p) = self_or_default(@_);
1061 return $self->end_html(@p);
1065 'SplitParam' => <<'END_OF_FUNC',
1068 my (@params) = split ("\0", $param);
1069 return (wantarray ? @params : $params[0]);
1073 'MethGet' => <<'END_OF_FUNC',
1075 return request_method() eq 'GET';
1079 'MethPost' => <<'END_OF_FUNC',
1081 return request_method() eq 'POST';
1085 'TIEHASH' => <<'END_OF_FUNC',
1089 if (ref($arg) && UNIVERSAL::isa($arg,'CGI')) {
1092 return $Q ||= $class->new(@_);
1096 'STORE' => <<'END_OF_FUNC',
1101 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
1102 $self->param(-name=>$tag,-value=>\@vals);
1106 'FETCH' => <<'END_OF_FUNC',
1108 return $_[0] if $_[1] eq 'CGI';
1109 return undef unless defined $_[0]->param($_[1]);
1110 return join("\0",$_[0]->param($_[1]));
1114 'FIRSTKEY' => <<'END_OF_FUNC',
1116 $_[0]->{'.iterator'}=0;
1117 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1121 'NEXTKEY' => <<'END_OF_FUNC',
1123 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1127 'EXISTS' => <<'END_OF_FUNC',
1129 exists $_[0]->{$_[1]};
1133 'DELETE' => <<'END_OF_FUNC',
1135 $_[0]->delete($_[1]);
1139 'CLEAR' => <<'END_OF_FUNC',
1147 # Append a new value to an existing query
1149 'append' => <<'EOF',
1151 my($self,@p) = self_or_default(@_);
1152 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
1153 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
1155 $self->add_parameter($name);
1156 push(@{$self->{$name}},@values);
1158 return $self->param($name);
1162 #### Method: delete_all
1163 # Delete all parameters
1165 'delete_all' => <<'EOF',
1167 my($self) = self_or_default(@_);
1168 my @param = $self->param();
1169 $self->delete(@param);
1173 'Delete' => <<'EOF',
1175 my($self,@p) = self_or_default(@_);
1180 'Delete_all' => <<'EOF',
1182 my($self,@p) = self_or_default(@_);
1183 $self->delete_all(@p);
1187 #### Method: autoescape
1188 # If you want to turn off the autoescaping features,
1189 # call this method with undef as the argument
1190 'autoEscape' => <<'END_OF_FUNC',
1192 my($self,$escape) = self_or_default(@_);
1193 my $d = $self->{'escape'};
1194 $self->{'escape'} = $escape;
1200 #### Method: version
1201 # Return the current version
1203 'version' => <<'END_OF_FUNC',
1209 #### Method: url_param
1210 # Return a parameter in the QUERY_STRING, regardless of
1211 # whether this was a POST or a GET
1213 'url_param' => <<'END_OF_FUNC',
1215 my ($self,@p) = self_or_default(@_);
1216 my $name = shift(@p);
1217 return undef unless exists($ENV{QUERY_STRING});
1218 unless (exists($self->{'.url_param'})) {
1219 $self->{'.url_param'}={}; # empty hash
1220 if ($ENV{QUERY_STRING} =~ /=/) {
1221 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
1224 ($param,$value) = split('=',$_,2);
1225 $param = unescape($param);
1226 $value = unescape($value);
1227 push(@{$self->{'.url_param'}->{$param}},$value);
1230 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1233 return keys %{$self->{'.url_param'}} unless defined($name);
1234 return () unless $self->{'.url_param'}->{$name};
1235 return wantarray ? @{$self->{'.url_param'}->{$name}}
1236 : $self->{'.url_param'}->{$name}->[0];
1241 # Returns a string in which all the known parameter/value
1242 # pairs are represented as nested lists, mainly for the purposes
1245 'Dump' => <<'END_OF_FUNC',
1247 my($self) = self_or_default(@_);
1248 my($param,$value,@result);
1249 return '<ul></ul>' unless $self->param;
1250 push(@result,"<ul>");
1251 foreach $param ($self->param) {
1252 my($name)=$self->escapeHTML($param);
1253 push(@result,"<li><strong>$param</strong></li>");
1254 push(@result,"<ul>");
1255 foreach $value ($self->param($param)) {
1256 $value = $self->escapeHTML($value);
1257 $value =~ s/\n/<br \/>\n/g;
1258 push(@result,"<li>$value</li>");
1260 push(@result,"</ul>");
1262 push(@result,"</ul>");
1263 return join("\n",@result);
1267 #### Method as_string
1269 # synonym for "dump"
1271 'as_string' => <<'END_OF_FUNC',
1278 # Write values out to a filehandle in such a way that they can
1279 # be reinitialized by the filehandle form of the new() method
1281 'save' => <<'END_OF_FUNC',
1283 my($self,$filehandle) = self_or_default(@_);
1284 $filehandle = to_filehandle($filehandle);
1286 local($,) = ''; # set print field separator back to a sane value
1287 local($\) = ''; # set output line separator to a sane value
1288 foreach $param ($self->param) {
1289 my($escaped_param) = escape($param);
1291 foreach $value ($self->param($param)) {
1292 print $filehandle "$escaped_param=",escape("$value"),"\n";
1295 foreach (keys %{$self->{'.fieldnames'}}) {
1296 print $filehandle ".cgifields=",escape("$_"),"\n";
1298 print $filehandle "=\n"; # end of record
1303 #### Method: save_parameters
1304 # An alias for save() that is a better name for exportation.
1305 # Only intended to be used with the function (non-OO) interface.
1307 'save_parameters' => <<'END_OF_FUNC',
1308 sub save_parameters {
1310 return save(to_filehandle($fh));
1314 #### Method: restore_parameters
1315 # A way to restore CGI parameters from an initializer.
1316 # Only intended to be used with the function (non-OO) interface.
1318 'restore_parameters' => <<'END_OF_FUNC',
1319 sub restore_parameters {
1320 $Q = $CGI::DefaultClass->new(@_);
1324 #### Method: multipart_init
1325 # Return a Content-Type: style header for server-push
1326 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1328 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1329 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1331 'multipart_init' => <<'END_OF_FUNC',
1332 sub multipart_init {
1333 my($self,@p) = self_or_default(@_);
1334 my($boundary,@other) = rearrange([BOUNDARY],@p);
1335 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1336 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1337 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1338 $type = SERVER_PUSH($boundary);
1339 return $self->header(
1342 (map { split "=", $_, 2 } @other),
1343 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1348 #### Method: multipart_start
1349 # Return a Content-Type: style header for server-push, start of section
1351 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1352 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1354 'multipart_start' => <<'END_OF_FUNC',
1355 sub multipart_start {
1357 my($self,@p) = self_or_default(@_);
1358 my($type,@other) = rearrange([TYPE],@p);
1359 $type = $type || 'text/html';
1360 push(@header,"Content-Type: $type");
1362 # rearrange() was designed for the HTML portion, so we
1363 # need to fix it up a little.
1365 # Don't use \s because of perl bug 21951
1366 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1367 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1369 push(@header,@other);
1370 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1376 #### Method: multipart_end
1377 # Return a MIME boundary separator for server-push, end of section
1379 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1382 'multipart_end' => <<'END_OF_FUNC',
1384 my($self,@p) = self_or_default(@_);
1385 return $self->{'separator'};
1390 #### Method: multipart_final
1391 # Return a MIME boundary separator for server-push, end of all sections
1393 # Contributed by Andrew Benham (adsb@bigfoot.com)
1395 'multipart_final' => <<'END_OF_FUNC',
1396 sub multipart_final {
1397 my($self,@p) = self_or_default(@_);
1398 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1404 # Return a Content-Type: style header
1407 'header' => <<'END_OF_FUNC',
1409 my($self,@p) = self_or_default(@_);
1412 return "" if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1414 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,$p3p,@other) =
1415 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1416 'STATUS',['COOKIE','COOKIES'],'TARGET',
1417 'EXPIRES','NPH','CHARSET',
1418 'ATTACHMENT','P3P'],@p);
1422 $type ||= 'text/html' unless defined($type);
1424 if (defined $charset) {
1425 $self->charset($charset);
1427 $charset = $self->charset if $type =~ /^text\//;
1430 # rearrange() was designed for the HTML portion, so we
1431 # need to fix it up a little.
1433 # Don't use \s because of perl bug 21951
1434 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1435 ($_ = $header) =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e;
1438 $type .= "; charset=$charset" if $type ne '' and $type !~ /\bcharset\b/ and $charset ne '';
1440 # Maybe future compatibility. Maybe not.
1441 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1442 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1443 push(@header,"Server: " . &server_software()) if $nph;
1445 push(@header,"Status: $status") if $status;
1446 push(@header,"Window-Target: $target") if $target;
1448 $p3p = join ' ',@$p3p if ref($p3p) eq 'ARRAY';
1449 push(@header,qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p"));
1451 # push all the cookies -- there may be several
1453 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1455 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1456 push(@header,"Set-Cookie: $cs") if $cs ne '';
1459 # if the user indicates an expiration time, then we need
1460 # both an Expires and a Date header (so that the browser is
1462 push(@header,"Expires: " . expires($expires,'http'))
1464 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1465 push(@header,"Pragma: no-cache") if $self->cache();
1466 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1467 push(@header,map {ucfirst $_} @other);
1468 push(@header,"Content-Type: $type") if $type ne '';
1469 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1470 if ($MOD_PERL and not $nph) {
1471 $self->r->send_cgi_header($header);
1480 # Control whether header() will produce the no-cache
1483 'cache' => <<'END_OF_FUNC',
1485 my($self,$new_value) = self_or_default(@_);
1486 $new_value = '' unless $new_value;
1487 if ($new_value ne '') {
1488 $self->{'cache'} = $new_value;
1490 return $self->{'cache'};
1495 #### Method: redirect
1496 # Return a Location: style header
1499 'redirect' => <<'END_OF_FUNC',
1501 my($self,@p) = self_or_default(@_);
1502 my($url,$target,$status,$cookie,$nph,@other) =
1503 rearrange([[LOCATION,URI,URL],TARGET,STATUS,['COOKIE','COOKIES'],NPH],@p);
1504 $status = '302 Found' unless defined $status;
1505 $url ||= $self->self_url;
1507 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1509 '-Status' => $status,
1512 unshift(@o,'-Target'=>$target) if $target;
1513 unshift(@o,'-Type'=>'');
1515 unshift(@unescaped,'-Cookie'=>$cookie) if $cookie;
1516 return $self->header((map {$self->unescapeHTML($_)} @o),@unescaped);
1521 #### Method: start_html
1522 # Canned HTML header
1525 # $title -> (optional) The title for this HTML document (-title)
1526 # $author -> (optional) e-mail address of the author (-author)
1527 # $base -> (optional) if set to true, will enter the BASE address of this document
1528 # for resolving relative references (-base)
1529 # $xbase -> (optional) alternative base at some remote location (-xbase)
1530 # $target -> (optional) target window to load all links into (-target)
1531 # $script -> (option) Javascript code (-script)
1532 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1533 # $meta -> (optional) Meta information tags
1534 # $head -> (optional) any other elements you'd like to incorporate into the <head> tag
1535 # (a scalar or array ref)
1536 # $style -> (optional) reference to an external style sheet
1537 # @other -> (optional) any other named parameters you'd like to incorporate into
1540 'start_html' => <<'END_OF_FUNC',
1542 my($self,@p) = &self_or_default(@_);
1543 my($title,$author,$base,$xbase,$script,$noscript,
1544 $target,$meta,$head,$style,$dtd,$lang,$encoding,$declare_xml,@other) =
1545 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,
1546 META,HEAD,STYLE,DTD,LANG,ENCODING,DECLARE_XML],@p);
1548 $self->element_id(0);
1549 $self->element_tab(0);
1551 $encoding = lc($self->charset) unless defined $encoding;
1553 # Need to sort out the DTD before it's okay to call escapeHTML().
1554 my(@result,$xml_dtd);
1556 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1557 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1559 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1562 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1565 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1566 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1567 push @result,qq(<?xml version="1.0" encoding="$encoding"?>) if $xml_dtd && $declare_xml;
1569 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1570 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t "$dtd->[1]">));
1571 $DTD_PUBLIC_IDENTIFIER = $dtd->[0];
1573 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1574 $DTD_PUBLIC_IDENTIFIER = $dtd;
1577 # Now that we know whether we're using the HTML 3.2 DTD or not, it's okay to
1578 # call escapeHTML(). Strangely enough, the title needs to be escaped as
1579 # HTML while the author needs to be escaped as a URL.
1580 $title = $self->escapeHTML($title || 'Untitled Document');
1581 $author = $self->escape($author);
1583 if ($DTD_PUBLIC_IDENTIFIER =~ /[^X]HTML (2\.0|3\.2)/i) {
1584 $lang = "" unless defined $lang;
1588 $lang = 'en-US' unless defined $lang;
1591 my $lang_bits = $lang ne '' ? qq( lang="$lang" xml:lang="$lang") : '';
1592 my $meta_bits = qq(<meta http-equiv="Content-Type" content="text/html; charset=$encoding" />)
1593 if $XHTML && $encoding && !$declare_xml;
1595 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml"$lang_bits>\n<head>\n<title>$title</title>)
1596 : ($lang ? qq(<html lang="$lang">) : "<html>")
1597 . "<head><title>$title</title>");
1598 if (defined $author) {
1599 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1600 : "<link rev=\"made\" href=\"mailto:$author\">");
1603 if ($base || $xbase || $target) {
1604 my $href = $xbase || $self->url('-path'=>1);
1605 my $t = $target ? qq/ target="$target"/ : '';
1606 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1609 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1610 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1611 : qq(<meta name="$_" content="$meta->{$_}">)); }
1614 push(@result,ref($head) ? @$head : $head) if $head;
1616 # handle the infrequently-used -style and -script parameters
1617 push(@result,$self->_style($style)) if defined $style;
1618 push(@result,$self->_script($script)) if defined $script;
1619 push(@result,$meta_bits) if defined $meta_bits;
1621 # handle -noscript parameter
1622 push(@result,<<END) if $noscript;
1628 my($other) = @other ? " @other" : '';
1629 push(@result,"</head>\n<body$other>\n");
1630 return join("\n",@result);
1635 # internal method for generating a CSS style section
1637 '_style' => <<'END_OF_FUNC',
1639 my ($self,$style) = @_;
1641 my $type = 'text/css';
1643 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1644 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1646 my @s = ref($style) eq 'ARRAY' ? @$style : $style;
1650 my($src,$code,$verbatim,$stype,$foo,@other) =
1651 rearrange([qw(SRC CODE VERBATIM TYPE FOO)],
1653 ref($s) eq 'ARRAY' ? @$s : %$s));
1654 $type = $stype if $stype;
1655 my $other = @other ? join ' ',@other : '';
1657 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1658 { # If it is, push a LINK tag for each one
1659 foreach $src (@$src)
1661 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1662 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)) if $src;
1666 { # Otherwise, push the single -src, if it exists.
1667 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1668 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)
1672 my @v = ref($verbatim) eq 'ARRAY' ? @$verbatim : $verbatim;
1673 push(@result, "<style type=\"text/css\">\n$_\n</style>") foreach @v;
1675 my @c = ref($code) eq 'ARRAY' ? @$code : $code if $code;
1676 push(@result,style({'type'=>$type},"$cdata_start\n$_\n$cdata_end")) foreach @c;
1680 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1681 : qq(<link rel="stylesheet" type="$type" href="$src"$other>));
1688 '_script' => <<'END_OF_FUNC',
1690 my ($self,$script) = @_;
1693 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1694 foreach $script (@scripts) {
1695 my($src,$code,$language);
1696 if (ref($script)) { # script is a hash
1697 ($src,$code,$language, $type) =
1698 rearrange([SRC,CODE,LANGUAGE,TYPE],
1699 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1700 ref($script) eq 'ARRAY' ? @$script : %$script);
1701 # User may not have specified language
1702 $language ||= 'JavaScript';
1703 unless (defined $type) {
1704 $type = lc $language;
1705 # strip '1.2' from 'javascript1.2'
1706 $type =~ s/^(\D+).*$/text\/$1/;
1709 ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
1712 my $comment = '//'; # javascript by default
1713 $comment = '#' if $type=~/perl|tcl/i;
1714 $comment = "'" if $type=~/vbscript/i;
1716 my ($cdata_start,$cdata_end);
1718 $cdata_start = "$comment<![CDATA[\n";
1719 $cdata_end .= "\n$comment]]>";
1721 $cdata_start = "\n<!-- Hide script\n";
1722 $cdata_end = $comment;
1723 $cdata_end .= " End script hiding -->\n";
1726 push(@satts,'src'=>$src) if $src;
1727 push(@satts,'language'=>$language) unless defined $type;
1728 push(@satts,'type'=>$type);
1729 $code = $cdata_start . $code . $cdata_end if defined $code;
1730 push(@result,$self->script({@satts},$code || ''));
1736 #### Method: end_html
1737 # End an HTML document.
1738 # Trivial method for completeness. Just returns "</body>"
1740 'end_html' => <<'END_OF_FUNC',
1742 return "\n</body>\n</html>";
1747 ################################
1748 # METHODS USED IN BUILDING FORMS
1749 ################################
1751 #### Method: isindex
1752 # Just prints out the isindex tag.
1754 # $action -> optional URL of script to run
1756 # A string containing a <isindex> tag
1757 'isindex' => <<'END_OF_FUNC',
1759 my($self,@p) = self_or_default(@_);
1760 my($action,@other) = rearrange([ACTION],@p);
1761 $action = qq/ action="$action"/ if $action;
1762 my($other) = @other ? " @other" : '';
1763 return $XHTML ? "<isindex$action$other />" : "<isindex$action$other>";
1768 #### Method: startform
1771 # $method -> optional submission method to use (GET or POST)
1772 # $action -> optional URL of script to run
1773 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1774 'startform' => <<'END_OF_FUNC',
1776 my($self,@p) = self_or_default(@_);
1778 my($method,$action,$enctype,@other) =
1779 rearrange([METHOD,ACTION,ENCTYPE],@p);
1781 $method = $self->escapeHTML(lc($method) || 'post');
1782 $enctype = $self->escapeHTML($enctype || &URL_ENCODED);
1783 if (defined $action) {
1784 $action = $self->escapeHTML($action);
1787 $action = $self->escapeHTML($self->request_uri);
1789 $action = qq(action="$action");
1790 my($other) = @other ? " @other" : '';
1791 $self->{'.parametersToAdd'}={};
1792 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1797 #### Method: start_form
1798 # synonym for startform
1799 'start_form' => <<'END_OF_FUNC',
1801 $XHTML ? &start_multipart_form : &startform;
1805 'end_multipart_form' => <<'END_OF_FUNC',
1806 sub end_multipart_form {
1811 #### Method: start_multipart_form
1812 # synonym for startform
1813 'start_multipart_form' => <<'END_OF_FUNC',
1814 sub start_multipart_form {
1815 my($self,@p) = self_or_default(@_);
1816 if (defined($p[0]) && substr($p[0],0,1) eq '-') {
1818 $p{'-enctype'}=&MULTIPART;
1819 return $self->startform(%p);
1821 my($method,$action,@other) =
1822 rearrange([METHOD,ACTION],@p);
1823 return $self->startform($method,$action,&MULTIPART,@other);
1829 #### Method: endform
1831 'endform' => <<'END_OF_FUNC',
1833 my($self,@p) = self_or_default(@_);
1835 return wantarray ? ("</form>") : "\n</form>";
1837 if (my @fields = $self->get_fields) {
1838 return wantarray ? ("<div>",@fields,"</div>","</form>")
1839 : "<div>".(join '',@fields)."</div>\n</form>";
1848 '_textfield' => <<'END_OF_FUNC',
1850 my($self,$tag,@p) = self_or_default(@_);
1851 my($name,$default,$size,$maxlength,$override,$tabindex,@other) =
1852 rearrange([NAME,[DEFAULT,VALUE,VALUES],SIZE,MAXLENGTH,[OVERRIDE,FORCE],TABINDEX],@p);
1854 my $current = $override ? $default :
1855 (defined($self->param($name)) ? $self->param($name) : $default);
1857 $current = defined($current) ? $self->escapeHTML($current,1) : '';
1858 $name = defined($name) ? $self->escapeHTML($name) : '';
1859 my($s) = defined($size) ? qq/ size="$size"/ : '';
1860 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1861 my($other) = @other ? " @other" : '';
1862 # this entered at cristy's request to fix problems with file upload fields
1863 # and WebTV -- not sure it won't break stuff
1864 my($value) = $current ne '' ? qq(value="$current") : '';
1865 $tabindex = $self->element_tab($tabindex);
1866 return $XHTML ? qq(<input type="$tag" name="$name" $tabindex$value$s$m$other />)
1867 : qq(<input type="$tag" name="$name" $value$s$m$other>);
1871 #### Method: textfield
1873 # $name -> Name of the text field
1874 # $default -> Optional default value of the field if not
1876 # $size -> Optional width of field in characaters.
1877 # $maxlength -> Optional maximum number of characters.
1879 # A string containing a <input type="text"> field
1881 'textfield' => <<'END_OF_FUNC',
1883 my($self,@p) = self_or_default(@_);
1884 $self->_textfield('text',@p);
1889 #### Method: filefield
1891 # $name -> Name of the file upload field
1892 # $size -> Optional width of field in characaters.
1893 # $maxlength -> Optional maximum number of characters.
1895 # A string containing a <input type="file"> field
1897 'filefield' => <<'END_OF_FUNC',
1899 my($self,@p) = self_or_default(@_);
1900 $self->_textfield('file',@p);
1905 #### Method: password
1906 # Create a "secret password" entry field
1908 # $name -> Name of the field
1909 # $default -> Optional default value of the field if not
1911 # $size -> Optional width of field in characters.
1912 # $maxlength -> Optional maximum characters that can be entered.
1914 # A string containing a <input type="password"> field
1916 'password_field' => <<'END_OF_FUNC',
1917 sub password_field {
1918 my ($self,@p) = self_or_default(@_);
1919 $self->_textfield('password',@p);
1923 #### Method: textarea
1925 # $name -> Name of the text field
1926 # $default -> Optional default value of the field if not
1928 # $rows -> Optional number of rows in text area
1929 # $columns -> Optional number of columns in text area
1931 # A string containing a <textarea></textarea> tag
1933 'textarea' => <<'END_OF_FUNC',
1935 my($self,@p) = self_or_default(@_);
1936 my($name,$default,$rows,$cols,$override,$tabindex,@other) =
1937 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE],TABINDEX],@p);
1939 my($current)= $override ? $default :
1940 (defined($self->param($name)) ? $self->param($name) : $default);
1942 $name = defined($name) ? $self->escapeHTML($name) : '';
1943 $current = defined($current) ? $self->escapeHTML($current) : '';
1944 my($r) = $rows ? qq/ rows="$rows"/ : '';
1945 my($c) = $cols ? qq/ cols="$cols"/ : '';
1946 my($other) = @other ? " @other" : '';
1947 $tabindex = $self->element_tab($tabindex);
1948 return qq{<textarea name="$name" $tabindex$r$c$other>$current</textarea>};
1954 # Create a javascript button.
1956 # $name -> (optional) Name for the button. (-name)
1957 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1958 # $onclick -> (optional) Text of the JavaScript to run when the button is
1961 # A string containing a <input type="button"> tag
1963 'button' => <<'END_OF_FUNC',
1965 my($self,@p) = self_or_default(@_);
1967 my($label,$value,$script,$tabindex,@other) = rearrange([NAME,[VALUE,LABEL],
1968 [ONCLICK,SCRIPT],TABINDEX],@p);
1970 $label=$self->escapeHTML($label);
1971 $value=$self->escapeHTML($value,1);
1972 $script=$self->escapeHTML($script);
1975 $name = qq/ name="$label"/ if $label;
1976 $value = $value || $label;
1978 $val = qq/ value="$value"/ if $value;
1979 $script = qq/ onclick="$script"/ if $script;
1980 my($other) = @other ? " @other" : '';
1981 $tabindex = $self->element_tab($tabindex);
1982 return $XHTML ? qq(<input type="button" $tabindex$name$val$script$other />)
1983 : qq(<input type="button"$name$val$script$other>);
1989 # Create a "submit query" button.
1991 # $name -> (optional) Name for the button.
1992 # $value -> (optional) Value of the button when selected (also doubles as label).
1993 # $label -> (optional) Label printed on the button(also doubles as the value).
1995 # A string containing a <input type="submit"> tag
1997 'submit' => <<'END_OF_FUNC',
1999 my($self,@p) = self_or_default(@_);
2001 my($label,$value,$tabindex,@other) = rearrange([NAME,[VALUE,LABEL],TABINDEX],@p);
2003 $label=$self->escapeHTML($label);
2004 $value=$self->escapeHTML($value,1);
2006 my $name = $NOSTICKY ? '' : 'name=".submit" ';
2007 $name = qq/name="$label" / if defined($label);
2008 $value = defined($value) ? $value : $label;
2010 $val = qq/value="$value" / if defined($value);
2011 $tabindex = $self->element_tab($tabindex);
2012 my($other) = @other ? "@other " : '';
2013 return $XHTML ? qq(<input type="submit" $tabindex$name$val$other/>)
2014 : qq(<input type="submit" $name$val$other>);
2020 # Create a "reset" button.
2022 # $name -> (optional) Name for the button.
2024 # A string containing a <input type="reset"> tag
2026 'reset' => <<'END_OF_FUNC',
2028 my($self,@p) = self_or_default(@_);
2029 my($label,$value,$tabindex,@other) = rearrange(['NAME',['VALUE','LABEL'],TABINDEX],@p);
2030 $label=$self->escapeHTML($label);
2031 $value=$self->escapeHTML($value,1);
2032 my ($name) = ' name=".reset"';
2033 $name = qq/ name="$label"/ if defined($label);
2034 $value = defined($value) ? $value : $label;
2036 $val = qq/ value="$value"/ if defined($value);
2037 my($other) = @other ? " @other" : '';
2038 $tabindex = $self->element_tab($tabindex);
2039 return $XHTML ? qq(<input type="reset" $tabindex$name$val$other />)
2040 : qq(<input type="reset"$name$val$other>);
2045 #### Method: defaults
2046 # Create a "defaults" button.
2048 # $name -> (optional) Name for the button.
2050 # A string containing a <input type="submit" name=".defaults"> tag
2052 # Note: this button has a special meaning to the initialization script,
2053 # and tells it to ERASE the current query string so that your defaults
2056 'defaults' => <<'END_OF_FUNC',
2058 my($self,@p) = self_or_default(@_);
2060 my($label,$tabindex,@other) = rearrange([[NAME,VALUE],TABINDEX],@p);
2062 $label=$self->escapeHTML($label,1);
2063 $label = $label || "Defaults";
2064 my($value) = qq/ value="$label"/;
2065 my($other) = @other ? " @other" : '';
2066 $tabindex = $self->element_tab($tabindex);
2067 return $XHTML ? qq(<input type="submit" name=".defaults" $tabindex$value$other />)
2068 : qq/<input type="submit" NAME=".defaults"$value$other>/;
2073 #### Method: comment
2074 # Create an HTML <!-- comment -->
2075 # Parameters: a string
2076 'comment' => <<'END_OF_FUNC',
2078 my($self,@p) = self_or_CGI(@_);
2079 return "<!-- @p -->";
2083 #### Method: checkbox
2084 # Create a checkbox that is not logically linked to any others.
2085 # The field value is "on" when the button is checked.
2087 # $name -> Name of the checkbox
2088 # $checked -> (optional) turned on by default if true
2089 # $value -> (optional) value of the checkbox, 'on' by default
2090 # $label -> (optional) a user-readable label printed next to the box.
2091 # Otherwise the checkbox name is used.
2093 # A string containing a <input type="checkbox"> field
2095 'checkbox' => <<'END_OF_FUNC',
2097 my($self,@p) = self_or_default(@_);
2099 my($name,$checked,$value,$label,$override,$tabindex,@other) =
2100 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE],TABINDEX],@p);
2102 $value = defined $value ? $value : 'on';
2104 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2105 defined $self->param($name))) {
2106 $checked = grep($_ eq $value,$self->param($name)) ? $self->_checked(1) : '';
2108 $checked = $self->_checked($checked);
2110 my($the_label) = defined $label ? $label : $name;
2111 $name = $self->escapeHTML($name);
2112 $value = $self->escapeHTML($value,1);
2113 $the_label = $self->escapeHTML($the_label);
2114 my($other) = @other ? "@other " : '';
2115 $tabindex = $self->element_tab($tabindex);
2116 $self->register_parameter($name);
2117 return $XHTML ? CGI::label(qq{<input type="checkbox" name="$name" value="$value" $tabindex$checked$other/>$the_label})
2118 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
2124 # Escape HTML -- used internally
2125 'escapeHTML' => <<'END_OF_FUNC',
2127 # hack to work around earlier hacks
2128 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
2129 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
2130 return undef unless defined($toencode);
2131 return $toencode if ref($self) && !$self->{'escape'};
2132 $toencode =~ s{&}{&}gso;
2133 $toencode =~ s{<}{<}gso;
2134 $toencode =~ s{>}{>}gso;
2135 if ($DTD_PUBLIC_IDENTIFIER =~ /[^X]HTML 3\.2/i) {
2136 # $quot; was accidentally omitted from the HTML 3.2 DTD -- see
2137 # <http://validator.w3.org/docs/errors.html#bad-entity> /
2138 # <http://lists.w3.org/Archives/Public/www-html/1997Mar/0003.html>.
2139 $toencode =~ s{"}{"}gso;
2142 $toencode =~ s{"}{"}gso;
2144 my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
2145 uc $self->{'.charset'} eq 'WINDOWS-1252';
2146 if ($latin) { # bug in some browsers
2147 $toencode =~ s{'}{'}gso;
2148 $toencode =~ s{\x8b}{‹}gso;
2149 $toencode =~ s{\x9b}{›}gso;
2150 if (defined $newlinestoo && $newlinestoo) {
2151 $toencode =~ s{\012}{ }gso;
2152 $toencode =~ s{\015}{ }gso;
2159 # unescape HTML -- used internally
2160 'unescapeHTML' => <<'END_OF_FUNC',
2162 # hack to work around earlier hacks
2163 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
2164 my ($self,$string) = CGI::self_or_default(@_);
2165 return undef unless defined($string);
2166 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
2168 # thanks to Randal Schwartz for the correct solution to this one
2169 $string=~ s[&(.*?);]{
2175 /^#(\d+)$/ && $latin ? chr($1) :
2176 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
2183 # Internal procedure - don't use
2184 '_tableize' => <<'END_OF_FUNC',
2186 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
2187 my @rowheaders = $rowheaders ? @$rowheaders : ();
2188 my @colheaders = $colheaders ? @$colheaders : ();
2191 if (defined($columns)) {
2192 $rows = int(0.99 + @elements/$columns) unless defined($rows);
2194 if (defined($rows)) {
2195 $columns = int(0.99 + @elements/$rows) unless defined($columns);
2198 # rearrange into a pretty table
2199 $result = "<table>";
2201 unshift(@colheaders,'') if @colheaders && @rowheaders;
2202 $result .= "<tr>" if @colheaders;
2203 foreach (@colheaders) {
2204 $result .= "<th>$_</th>";
2206 for ($row=0;$row<$rows;$row++) {
2208 $result .= "<th>$rowheaders[$row]</th>" if @rowheaders;
2209 for ($column=0;$column<$columns;$column++) {
2210 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
2211 if defined($elements[$column*$rows + $row]);
2215 $result .= "</table>";
2221 #### Method: radio_group
2222 # Create a list of logically-linked radio buttons.
2224 # $name -> Common name for all the buttons.
2225 # $values -> A pointer to a regular array containing the
2226 # values for each button in the group.
2227 # $default -> (optional) Value of the button to turn on by default. Pass '-'
2228 # to turn _nothing_ on.
2229 # $linebreak -> (optional) Set to true to place linebreaks
2230 # between the buttons.
2231 # $labels -> (optional)
2232 # A pointer to an associative array of labels to print next to each checkbox
2233 # in the form $label{'value'}="Long explanatory label".
2234 # Otherwise the provided values are used as the labels.
2236 # An ARRAY containing a series of <input type="radio"> fields
2238 'radio_group' => <<'END_OF_FUNC',
2240 my($self,@p) = self_or_default(@_);
2241 $self->_box_group('radio',@p);
2245 #### Method: checkbox_group
2246 # Create a list of logically-linked checkboxes.
2248 # $name -> Common name for all the check boxes
2249 # $values -> A pointer to a regular array containing the
2250 # values for each checkbox in the group.
2251 # $defaults -> (optional)
2252 # 1. If a pointer to a regular array of checkbox values,
2253 # then this will be used to decide which
2254 # checkboxes to turn on by default.
2255 # 2. If a scalar, will be assumed to hold the
2256 # value of a single checkbox in the group to turn on.
2257 # $linebreak -> (optional) Set to true to place linebreaks
2258 # between the buttons.
2259 # $labels -> (optional)
2260 # A pointer to an associative array of labels to print next to each checkbox
2261 # in the form $label{'value'}="Long explanatory label".
2262 # Otherwise the provided values are used as the labels.
2264 # An ARRAY containing a series of <input type="checkbox"> fields
2267 'checkbox_group' => <<'END_OF_FUNC',
2268 sub checkbox_group {
2269 my($self,@p) = self_or_default(@_);
2270 $self->_box_group('checkbox',@p);
2274 '_box_group' => <<'END_OF_FUNC',
2277 my $box_type = shift;
2279 my($name,$values,$defaults,$linebreak,$labels,$attributes,
2280 $rows,$columns,$rowheaders,$colheaders,
2281 $override,$nolabels,$tabindex,@other) =
2282 rearrange([ NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LINEBREAK,LABELS,ATTRIBUTES,
2283 ROWS,[COLUMNS,COLS],ROWHEADERS,COLHEADERS,
2284 [OVERRIDE,FORCE],NOLABELS,TABINDEX
2286 my($result,$checked);
2289 my(@elements,@values);
2290 @values = $self->_set_values_and_labels($values,\$labels,$name);
2291 my %checked = $self->previous_or_default($name,$defaults,$override);
2293 # If no check array is specified, check the first by default
2294 $checked{$values[0]}++ if $box_type eq 'radio' && !%checked;
2296 $name=$self->escapeHTML($name);
2299 if ($TABINDEX && $tabindex) {
2300 if (!ref $tabindex) {
2301 $self->element_tab($tabindex);
2302 } elsif (ref $tabindex eq 'ARRAY') {
2303 %tabs = map {$_=>$self->element_tab} @$tabindex;
2304 } elsif (ref $tabindex eq 'HASH') {
2308 %tabs = map {$_=>$self->element_tab} @values unless %tabs;
2310 my $other = @other ? "@other " : '';
2313 my $checkit = $self->_checked($box_type eq 'radio' ? ($checked{$_} && !$radio_checked++)
2317 $break = $XHTML ? "<br />" : "<br>";
2323 unless (defined($nolabels) && $nolabels) {
2325 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2326 $label = $self->escapeHTML($label,1);
2328 my $attribs = $self->_set_attributes($_, $attributes);
2329 my $tab = $tabs{$_};
2330 $_=$self->escapeHTML($_);
2334 qq(<input type="$box_type" name="$name" value="$_" $checkit$other$tab$attribs/>$label)).${break};
2336 push(@elements,qq/<input type="$box_type" name="$name" value="$_"$checkit$other$tab$attribs>${label}${break}/);
2339 $self->register_parameter($name);
2340 return wantarray ? @elements : "@elements"
2341 unless defined($columns) || defined($rows);
2342 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2347 #### Method: popup_menu
2348 # Create a popup menu.
2350 # $name -> Name for all the menu
2351 # $values -> A pointer to a regular array containing the
2352 # text of each menu item.
2353 # $default -> (optional) Default item to display
2354 # $labels -> (optional)
2355 # A pointer to an associative array of labels to print next to each checkbox
2356 # in the form $label{'value'}="Long explanatory label".
2357 # Otherwise the provided values are used as the labels.
2359 # A string containing the definition of a popup menu.
2361 'popup_menu' => <<'END_OF_FUNC',
2363 my($self,@p) = self_or_default(@_);
2365 my($name,$values,$default,$labels,$attributes,$override,$tabindex,@other) =
2366 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,
2367 ATTRIBUTES,[OVERRIDE,FORCE],TABINDEX],@p);
2368 my($result,$selected);
2370 if (!$override && defined($self->param($name))) {
2371 $selected = $self->param($name);
2373 $selected = $default;
2375 $name=$self->escapeHTML($name);
2376 my($other) = @other ? " @other" : '';
2379 @values = $self->_set_values_and_labels($values,\$labels,$name);
2380 $tabindex = $self->element_tab($tabindex);
2381 $result = qq/<select name="$name" $tabindex$other>\n/;
2384 foreach (split(/\n/)) {
2385 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2386 s/(value="$selected")/$selectit $1/ if defined $selected;
2391 my $attribs = $self->_set_attributes($_, $attributes);
2392 my($selectit) = defined($selected) ? $self->_selected($selected eq $_) : '';
2394 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2395 my($value) = $self->escapeHTML($_);
2396 $label=$self->escapeHTML($label,1);
2397 $result .= "<option $selectit${attribs}value=\"$value\">$label</option>\n";
2401 $result .= "</select>";
2407 #### Method: optgroup
2408 # Create a optgroup.
2410 # $name -> Label for the group
2411 # $values -> A pointer to a regular array containing the
2412 # values for each option line in the group.
2413 # $labels -> (optional)
2414 # A pointer to an associative array of labels to print next to each item
2415 # in the form $label{'value'}="Long explanatory label".
2416 # Otherwise the provided values are used as the labels.
2417 # $labeled -> (optional)
2418 # A true value indicates the value should be used as the label attribute
2419 # in the option elements.
2420 # The label attribute specifies the option label presented to the user.
2421 # This defaults to the content of the <option> element, but the label
2422 # attribute allows authors to more easily use optgroup without sacrificing
2423 # compatibility with browsers that do not support option groups.
2424 # $novals -> (optional)
2425 # A true value indicates to suppress the val attribute in the option elements
2427 # A string containing the definition of an option group.
2429 'optgroup' => <<'END_OF_FUNC',
2431 my($self,@p) = self_or_default(@_);
2432 my($name,$values,$attributes,$labeled,$noval,$labels,@other)
2433 = rearrange([NAME,[VALUES,VALUE],ATTRIBUTES,LABELED,NOVALS,LABELS],@p);
2435 my($result,@values);
2436 @values = $self->_set_values_and_labels($values,\$labels,$name,$labeled,$novals);
2437 my($other) = @other ? " @other" : '';
2439 $name=$self->escapeHTML($name);
2440 $result = qq/<optgroup label="$name"$other>\n/;
2443 foreach (split(/\n/)) {
2444 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2445 s/(value="$selected")/$selectit $1/ if defined $selected;
2450 my $attribs = $self->_set_attributes($_, $attributes);
2452 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2453 $label=$self->escapeHTML($label);
2454 my($value)=$self->escapeHTML($_,1);
2455 $result .= $labeled ? $novals ? "<option$attribs label=\"$value\">$label</option>\n"
2456 : "<option$attribs label=\"$value\" value=\"$value\">$label</option>\n"
2457 : $novals ? "<option$attribs>$label</option>\n"
2458 : "<option$attribs value=\"$value\">$label</option>\n";
2461 $result .= "</optgroup>";
2467 #### Method: scrolling_list
2468 # Create a scrolling list.
2470 # $name -> name for the list
2471 # $values -> A pointer to a regular array containing the
2472 # values for each option line in the list.
2473 # $defaults -> (optional)
2474 # 1. If a pointer to a regular array of options,
2475 # then this will be used to decide which
2476 # lines to turn on by default.
2477 # 2. Otherwise holds the value of the single line to turn on.
2478 # $size -> (optional) Size of the list.
2479 # $multiple -> (optional) If set, allow multiple selections.
2480 # $labels -> (optional)
2481 # A pointer to an associative array of labels to print next to each checkbox
2482 # in the form $label{'value'}="Long explanatory label".
2483 # Otherwise the provided values are used as the labels.
2485 # A string containing the definition of a scrolling list.
2487 'scrolling_list' => <<'END_OF_FUNC',
2488 sub scrolling_list {
2489 my($self,@p) = self_or_default(@_);
2490 my($name,$values,$defaults,$size,$multiple,$labels,$attributes,$override,$tabindex,@other)
2491 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2492 SIZE,MULTIPLE,LABELS,ATTRIBUTES,[OVERRIDE,FORCE],TABINDEX],@p);
2494 my($result,@values);
2495 @values = $self->_set_values_and_labels($values,\$labels,$name);
2497 $size = $size || scalar(@values);
2499 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2500 my($is_multiple) = $multiple ? qq/ multiple="multiple"/ : '';
2501 my($has_size) = $size ? qq/ size="$size"/: '';
2502 my($other) = @other ? " @other" : '';
2504 $name=$self->escapeHTML($name);
2505 $tabindex = $self->element_tab($tabindex);
2506 $result = qq/<select name="$name" $tabindex$has_size$is_multiple$other>\n/;
2508 my($selectit) = $self->_selected($selected{$_});
2510 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2511 $label=$self->escapeHTML($label);
2512 my($value)=$self->escapeHTML($_,1);
2513 my $attribs = $self->_set_attributes($_, $attributes);
2514 $result .= "<option ${selectit}${attribs}value=\"$value\">$label</option>\n";
2516 $result .= "</select>";
2517 $self->register_parameter($name);
2525 # $name -> Name of the hidden field
2526 # @default -> (optional) Initial values of field (may be an array)
2528 # $default->[initial values of field]
2530 # A string containing a <input type="hidden" name="name" value="value">
2532 'hidden' => <<'END_OF_FUNC',
2534 my($self,@p) = self_or_default(@_);
2536 # this is the one place where we departed from our standard
2537 # calling scheme, so we have to special-case (darn)
2539 my($name,$default,$override,@other) =
2540 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2542 my $do_override = 0;
2543 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2544 @value = ref($default) ? @{$default} : $default;
2545 $do_override = $override;
2547 foreach ($default,$override,@other) {
2548 push(@value,$_) if defined($_);
2552 # use previous values if override is not set
2553 my @prev = $self->param($name);
2554 @value = @prev if !$do_override && @prev;
2556 $name=$self->escapeHTML($name);
2558 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2559 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" @other />)
2560 : qq(<input type="hidden" name="$name" value="$_" @other>);
2562 return wantarray ? @result : join('',@result);
2567 #### Method: image_button
2569 # $name -> Name of the button
2570 # $src -> URL of the image source
2571 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2573 # A string containing a <input type="image" name="name" src="url" align="alignment">
2575 'image_button' => <<'END_OF_FUNC',
2577 my($self,@p) = self_or_default(@_);
2579 my($name,$src,$alignment,@other) =
2580 rearrange([NAME,SRC,ALIGN],@p);
2582 my($align) = $alignment ? " align=\U\"$alignment\"" : '';
2583 my($other) = @other ? " @other" : '';
2584 $name=$self->escapeHTML($name);
2585 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2586 : qq/<input type="image" name="$name" src="$src"$align$other>/;
2591 #### Method: self_url
2592 # Returns a URL containing the current script and all its
2593 # param/value pairs arranged as a query. You can use this
2594 # to create a link that, when selected, will reinvoke the
2595 # script with all its state information preserved.
2597 'self_url' => <<'END_OF_FUNC',
2599 my($self,@p) = self_or_default(@_);
2600 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2605 # This is provided as a synonym to self_url() for people unfortunate
2606 # enough to have incorporated it into their programs already!
2607 'state' => <<'END_OF_FUNC',
2615 # Like self_url, but doesn't return the query string part of
2618 'url' => <<'END_OF_FUNC',
2620 my($self,@p) = self_or_default(@_);
2621 my ($relative,$absolute,$full,$path_info,$query,$base,$rewrite) =
2622 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE','REWRITE'],@p);
2624 $full++ if $base || !($relative || $absolute);
2625 $rewrite++ unless defined $rewrite;
2627 my $path = $self->path_info;
2628 my $script_name = $self->script_name;
2629 my $request_uri = $self->request_uri || '';
2630 my $query_str = $self->query_string;
2632 my $rewrite_in_use = $request_uri && $request_uri !~ /^$script_name/;
2633 undef $path if $rewrite_in_use && $rewrite; # path not valid when rewriting active
2635 my $uri = $rewrite && $request_uri ? $request_uri : $script_name;
2636 $uri =~ s/\?.*$//; # remove query string
2637 $uri =~ s/$path$// if defined $path; # remove path
2640 my $protocol = $self->protocol();
2641 $url = "$protocol://";
2642 my $vh = http('x_forwarded_host') || http('host');
2646 $url .= server_name();
2647 my $port = $self->server_port;
2649 unless (lc($protocol) eq 'http' && $port == 80)
2650 || (lc($protocol) eq 'https' && $port == 443);
2652 return $url if $base;
2654 } elsif ($relative) {
2655 ($url) = $script_name =~ m!([^/]+)$!;
2656 } elsif ($absolute) {
2660 $url .= $path if $path_info and defined $path;
2661 $url .= "?$query_str" if $query and $query_str ne '';
2662 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/sprintf("%%%02X",ord($1))/eg;
2669 # Set or read a cookie from the specified name.
2670 # Cookie can then be passed to header().
2671 # Usual rules apply to the stickiness of -value.
2673 # -name -> name for this cookie (optional)
2674 # -value -> value of this cookie (scalar, array or hash)
2675 # -path -> paths for which this cookie is valid (optional)
2676 # -domain -> internet domain in which this cookie is valid (optional)
2677 # -secure -> if true, cookie only passed through secure channel (optional)
2678 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2680 'cookie' => <<'END_OF_FUNC',
2682 my($self,@p) = self_or_default(@_);
2683 my($name,$value,$path,$domain,$secure,$expires) =
2684 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2686 require CGI::Cookie;
2688 # if no value is supplied, then we retrieve the
2689 # value of the cookie, if any. For efficiency, we cache the parsed
2690 # cookies in our state variables.
2691 unless ( defined($value) ) {
2692 $self->{'.cookies'} = CGI::Cookie->fetch
2693 unless $self->{'.cookies'};
2695 # If no name is supplied, then retrieve the names of all our cookies.
2696 return () unless $self->{'.cookies'};
2697 return keys %{$self->{'.cookies'}} unless $name;
2698 return () unless $self->{'.cookies'}->{$name};
2699 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2702 # If we get here, we're creating a new cookie
2703 return undef unless defined($name) && $name ne ''; # this is an error
2706 push(@param,'-name'=>$name);
2707 push(@param,'-value'=>$value);
2708 push(@param,'-domain'=>$domain) if $domain;
2709 push(@param,'-path'=>$path) if $path;
2710 push(@param,'-expires'=>$expires) if $expires;
2711 push(@param,'-secure'=>$secure) if $secure;
2713 return new CGI::Cookie(@param);
2717 'parse_keywordlist' => <<'END_OF_FUNC',
2718 sub parse_keywordlist {
2719 my($self,$tosplit) = @_;
2720 $tosplit = unescape($tosplit); # unescape the keywords
2721 $tosplit=~tr/+/ /; # pluses to spaces
2722 my(@keywords) = split(/\s+/,$tosplit);
2727 'param_fetch' => <<'END_OF_FUNC',
2729 my($self,@p) = self_or_default(@_);
2730 my($name) = rearrange([NAME],@p);
2731 unless (exists($self->{$name})) {
2732 $self->add_parameter($name);
2733 $self->{$name} = [];
2736 return $self->{$name};
2740 ###############################################
2741 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2742 ###############################################
2744 #### Method: path_info
2745 # Return the extra virtual path information provided
2746 # after the URL (if any)
2748 'path_info' => <<'END_OF_FUNC',
2750 my ($self,$info) = self_or_default(@_);
2751 if (defined($info)) {
2752 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2753 $self->{'.path_info'} = $info;
2754 } elsif (! defined($self->{'.path_info'}) ) {
2755 my (undef,$path_info) = $self->_name_and_path_from_env;
2756 $self->{'.path_info'} = $path_info || '';
2757 # hack to fix broken path info in IIS
2758 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2761 return $self->{'.path_info'};
2765 # WE USE THIS TO COMPENSATE FOR A BUG IN APACHE 2 PRESENT AT LEAST UP THROUGH 2.0.54
2766 '_name_and_path_from_env' => <<'END_OF_FUNC',
2767 sub _name_and_path_from_env {
2769 my $raw_script_name = $ENV{SCRIPT_NAME} || '';
2770 my $raw_path_info = $ENV{PATH_INFO} || '';
2771 my $uri = $ENV{REQUEST_URI} || '';
2773 if ($raw_script_name =~ m/$raw_path_info$/) {
2774 $raw_script_name =~ s/$raw_path_info$//;
2777 my @uri_double_slashes = $uri =~ m^(/{2,}?)^g;
2778 my @path_double_slashes = "$raw_script_name $raw_path_info" =~ m^(/{2,}?)^g;
2780 my $apache_bug = @uri_double_slashes != @path_double_slashes;
2781 return ($raw_script_name,$raw_path_info) unless $apache_bug;
2783 my $path_info_search = $raw_path_info;
2784 # these characters will not (necessarily) be escaped
2785 $path_info_search =~ s/([^a-zA-Z0-9$()':_.,+*\/;?=&-])/uc sprintf("%%%02x",ord($1))/eg;
2786 $path_info_search = quotemeta($path_info_search);
2787 $path_info_search =~ s!/!/+!g;
2788 if ($uri =~ m/^(.+)($path_info_search)/) {
2791 return ($raw_script_name,$raw_path_info);
2797 #### Method: request_method
2798 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2800 'request_method' => <<'END_OF_FUNC',
2801 sub request_method {
2802 return $ENV{'REQUEST_METHOD'};
2806 #### Method: content_type
2807 # Returns the content_type string
2809 'content_type' => <<'END_OF_FUNC',
2811 return $ENV{'CONTENT_TYPE'};
2815 #### Method: path_translated
2816 # Return the physical path information provided
2817 # by the URL (if any)
2819 'path_translated' => <<'END_OF_FUNC',
2820 sub path_translated {
2821 return $ENV{'PATH_TRANSLATED'};
2826 #### Method: request_uri
2827 # Return the literal request URI
2829 'request_uri' => <<'END_OF_FUNC',
2831 return $ENV{'REQUEST_URI'};
2836 #### Method: query_string
2837 # Synthesize a query string from our current
2840 'query_string' => <<'END_OF_FUNC',
2842 my($self) = self_or_default(@_);
2843 my($param,$value,@pairs);
2844 foreach $param ($self->param) {
2845 my($eparam) = escape($param);
2846 foreach $value ($self->param($param)) {
2847 $value = escape($value);
2848 next unless defined $value;
2849 push(@pairs,"$eparam=$value");
2852 foreach (keys %{$self->{'.fieldnames'}}) {
2853 push(@pairs,".cgifields=".escape("$_"));
2855 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2861 # Without parameters, returns an array of the
2862 # MIME types the browser accepts.
2863 # With a single parameter equal to a MIME
2864 # type, will return undef if the browser won't
2865 # accept it, 1 if the browser accepts it but
2866 # doesn't give a preference, or a floating point
2867 # value between 0.0 and 1.0 if the browser
2868 # declares a quantitative score for it.
2869 # This handles MIME type globs correctly.
2871 'Accept' => <<'END_OF_FUNC',
2873 my($self,$search) = self_or_CGI(@_);
2874 my(%prefs,$type,$pref,$pat);
2876 my(@accept) = split(',',$self->http('accept'));
2879 ($pref) = /q=(\d\.\d+|\d+)/;
2880 ($type) = m#(\S+/[^;]+)#;
2882 $prefs{$type}=$pref || 1;
2885 return keys %prefs unless $search;
2887 # if a search type is provided, we may need to
2888 # perform a pattern matching operation.
2889 # The MIME types use a glob mechanism, which
2890 # is easily translated into a perl pattern match
2892 # First return the preference for directly supported
2894 return $prefs{$search} if $prefs{$search};
2896 # Didn't get it, so try pattern matching.
2897 foreach (keys %prefs) {
2898 next unless /\*/; # not a pattern match
2899 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2900 $pat =~ s/\*/.*/g; # turn it into a pattern
2901 return $prefs{$_} if $search=~/$pat/;
2907 #### Method: user_agent
2908 # If called with no parameters, returns the user agent.
2909 # If called with one parameter, does a pattern match (case
2910 # insensitive) on the user agent.
2912 'user_agent' => <<'END_OF_FUNC',
2914 my($self,$match)=self_or_CGI(@_);
2915 return $self->http('user_agent') unless $match;
2916 return $self->http('user_agent') =~ /$match/i;
2921 #### Method: raw_cookie
2922 # Returns the magic cookies for the session.
2923 # The cookies are not parsed or altered in any way, i.e.
2924 # cookies are returned exactly as given in the HTTP
2925 # headers. If a cookie name is given, only that cookie's
2926 # value is returned, otherwise the entire raw cookie
2929 'raw_cookie' => <<'END_OF_FUNC',
2931 my($self,$key) = self_or_CGI(@_);
2933 require CGI::Cookie;
2935 if (defined($key)) {
2936 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2937 unless $self->{'.raw_cookies'};
2939 return () unless $self->{'.raw_cookies'};
2940 return () unless $self->{'.raw_cookies'}->{$key};
2941 return $self->{'.raw_cookies'}->{$key};
2943 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2947 #### Method: virtual_host
2948 # Return the name of the virtual_host, which
2949 # is not always the same as the server
2951 'virtual_host' => <<'END_OF_FUNC',
2953 my $vh = http('x_forwarded_host') || http('host') || server_name();
2954 $vh =~ s/:\d+$//; # get rid of port number
2959 #### Method: remote_host
2960 # Return the name of the remote host, or its IP
2961 # address if unavailable. If this variable isn't
2962 # defined, it returns "localhost" for debugging
2965 'remote_host' => <<'END_OF_FUNC',
2967 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2973 #### Method: remote_addr
2974 # Return the IP addr of the remote host.
2976 'remote_addr' => <<'END_OF_FUNC',
2978 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2983 #### Method: script_name
2984 # Return the partial URL to this script for
2985 # self-referencing scripts. Also see
2986 # self_url(), which returns a URL with all state information
2989 'script_name' => <<'END_OF_FUNC',
2991 my ($self,@p) = self_or_default(@_);
2993 $self->{'.script_name'} = shift;
2994 } elsif (!exists $self->{'.script_name'}) {
2995 my ($script_name,$path_info) = $self->_name_and_path_from_env();
2996 $self->{'.script_name'} = $script_name;
2998 return $self->{'.script_name'};
3003 #### Method: referer
3004 # Return the HTTP_REFERER: useful for generating
3007 'referer' => <<'END_OF_FUNC',
3009 my($self) = self_or_CGI(@_);
3010 return $self->http('referer');
3015 #### Method: server_name
3016 # Return the name of the server
3018 'server_name' => <<'END_OF_FUNC',
3020 return $ENV{'SERVER_NAME'} || 'localhost';
3024 #### Method: server_software
3025 # Return the name of the server software
3027 'server_software' => <<'END_OF_FUNC',
3028 sub server_software {
3029 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
3033 #### Method: virtual_port
3034 # Return the server port, taking virtual hosts into account
3036 'virtual_port' => <<'END_OF_FUNC',
3038 my($self) = self_or_default(@_);
3039 my $vh = $self->http('x_forwarded_host') || $self->http('host');
3040 my $protocol = $self->protocol;
3042 return ($vh =~ /:(\d+)$/)[0] || ($protocol eq 'https' ? 443 : 80);
3044 return $self->server_port();
3049 #### Method: server_port
3050 # Return the tcp/ip port the server is running on
3052 'server_port' => <<'END_OF_FUNC',
3054 return $ENV{'SERVER_PORT'} || 80; # for debugging
3058 #### Method: server_protocol
3059 # Return the protocol (usually HTTP/1.0)
3061 'server_protocol' => <<'END_OF_FUNC',
3062 sub server_protocol {
3063 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
3068 # Return the value of an HTTP variable, or
3069 # the list of variables if none provided
3071 'http' => <<'END_OF_FUNC',
3073 my ($self,$parameter) = self_or_CGI(@_);
3074 return $ENV{$parameter} if $parameter=~/^HTTP/;
3075 $parameter =~ tr/-/_/;
3076 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
3078 foreach (keys %ENV) {
3079 push(@p,$_) if /^HTTP/;
3086 # Return the value of HTTPS
3088 'https' => <<'END_OF_FUNC',
3091 my ($self,$parameter) = self_or_CGI(@_);
3092 return $ENV{HTTPS} unless $parameter;
3093 return $ENV{$parameter} if $parameter=~/^HTTPS/;
3094 $parameter =~ tr/-/_/;
3095 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
3097 foreach (keys %ENV) {
3098 push(@p,$_) if /^HTTPS/;
3104 #### Method: protocol
3105 # Return the protocol (http or https currently)
3107 'protocol' => <<'END_OF_FUNC',
3111 return 'https' if uc($self->https()) eq 'ON';
3112 return 'https' if $self->server_port == 443;
3113 my $prot = $self->server_protocol;
3114 my($protocol,$version) = split('/',$prot);
3115 return "\L$protocol\E";
3119 #### Method: remote_ident
3120 # Return the identity of the remote user
3121 # (but only if his host is running identd)
3123 'remote_ident' => <<'END_OF_FUNC',
3125 return $ENV{'REMOTE_IDENT'};
3130 #### Method: auth_type
3131 # Return the type of use verification/authorization in use, if any.
3133 'auth_type' => <<'END_OF_FUNC',
3135 return $ENV{'AUTH_TYPE'};
3140 #### Method: remote_user
3141 # Return the authorization name used for user
3144 'remote_user' => <<'END_OF_FUNC',
3146 return $ENV{'REMOTE_USER'};
3151 #### Method: user_name
3152 # Try to return the remote user's name by hook or by
3155 'user_name' => <<'END_OF_FUNC',
3157 my ($self) = self_or_CGI(@_);
3158 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
3162 #### Method: nosticky
3163 # Set or return the NOSTICKY global flag
3165 'nosticky' => <<'END_OF_FUNC',
3167 my ($self,$param) = self_or_CGI(@_);
3168 $CGI::NOSTICKY = $param if defined($param);
3169 return $CGI::NOSTICKY;
3174 # Set or return the NPH global flag
3176 'nph' => <<'END_OF_FUNC',
3178 my ($self,$param) = self_or_CGI(@_);
3179 $CGI::NPH = $param if defined($param);
3184 #### Method: private_tempfiles
3185 # Set or return the private_tempfiles global flag
3187 'private_tempfiles' => <<'END_OF_FUNC',
3188 sub private_tempfiles {
3189 my ($self,$param) = self_or_CGI(@_);
3190 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
3191 return $CGI::PRIVATE_TEMPFILES;
3194 #### Method: close_upload_files
3195 # Set or return the close_upload_files global flag
3197 'close_upload_files' => <<'END_OF_FUNC',
3198 sub close_upload_files {
3199 my ($self,$param) = self_or_CGI(@_);
3200 $CGI::CLOSE_UPLOAD_FILES = $param if defined($param);
3201 return $CGI::CLOSE_UPLOAD_FILES;
3206 #### Method: default_dtd
3207 # Set or return the default_dtd global
3209 'default_dtd' => <<'END_OF_FUNC',
3211 my ($self,$param,$param2) = self_or_CGI(@_);
3212 if (defined $param2 && defined $param) {
3213 $CGI::DEFAULT_DTD = [ $param, $param2 ];
3214 } elsif (defined $param) {
3215 $CGI::DEFAULT_DTD = $param;
3217 return $CGI::DEFAULT_DTD;
3221 # -------------- really private subroutines -----------------
3222 'previous_or_default' => <<'END_OF_FUNC',
3223 sub previous_or_default {
3224 my($self,$name,$defaults,$override) = @_;
3227 if (!$override && ($self->{'.fieldnames'}->{$name} ||
3228 defined($self->param($name)) ) ) {
3229 grep($selected{$_}++,$self->param($name));
3230 } elsif (defined($defaults) && ref($defaults) &&
3231 (ref($defaults) eq 'ARRAY')) {
3232 grep($selected{$_}++,@{$defaults});
3234 $selected{$defaults}++ if defined($defaults);
3241 'register_parameter' => <<'END_OF_FUNC',
3242 sub register_parameter {
3243 my($self,$param) = @_;
3244 $self->{'.parametersToAdd'}->{$param}++;
3248 'get_fields' => <<'END_OF_FUNC',
3251 return $self->CGI::hidden('-name'=>'.cgifields',
3252 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
3257 'read_from_cmdline' => <<'END_OF_FUNC',
3258 sub read_from_cmdline {
3262 if ($DEBUG && @ARGV) {
3264 } elsif ($DEBUG > 1) {
3265 require "shellwords.pl";
3266 print STDERR "(offline mode: enter name=value pairs on standard input; press ^D or ^Z when done)\n";
3267 chomp(@lines = <STDIN>); # remove newlines
3268 $input = join(" ",@lines);
3269 @words = &shellwords($input);
3276 if ("@words"=~/=/) {
3277 $query_string = join('&',@words);
3279 $query_string = join('+',@words);
3281 if ($query_string =~ /^(.*?)\?(.*)$/)
3286 return { 'query_string' => $query_string, 'subpath' => $subpath };
3291 # subroutine: read_multipart
3293 # Read multipart data and store it into our parameters.
3294 # An interesting feature is that if any of the parts is a file, we
3295 # create a temporary file and open up a filehandle on it so that the
3296 # caller can read from it if necessary.
3298 'read_multipart' => <<'END_OF_FUNC',
3299 sub read_multipart {
3300 my($self,$boundary,$length) = @_;
3301 my($buffer) = $self->new_MultipartBuffer($boundary,$length);
3302 return unless $buffer;
3305 while (!$buffer->eof) {
3306 %header = $buffer->readHeader;
3309 $self->cgi_error("400 Bad request (malformed multipart POST)");
3313 my($param)= $header{'Content-Disposition'}=~/ name="([^;]*)"/;
3316 # Bug: Netscape doesn't escape quotation marks in file names!!!
3317 my($filename) = $header{'Content-Disposition'}=~/ filename="([^;]*)"/;
3318 # Test for Opera's multiple upload feature
3319 my($multipart) = ( defined( $header{'Content-Type'} ) &&
3320 $header{'Content-Type'} =~ /multipart\/mixed/ ) ?
3323 # add this parameter to our list
3324 $self->add_parameter($param);
3326 # If no filename specified, then just read the data and assign it
3327 # to our parameter list.
3328 if ( ( !defined($filename) || $filename eq '' ) && !$multipart ) {
3329 my($value) = $buffer->readBody;
3331 push(@{$self->{$param}},$value);
3335 my ($tmpfile,$tmp,$filehandle);
3337 # If we get here, then we are dealing with a potentially large
3338 # uploaded form. Save the data to a temporary file, then open
3339 # the file for reading.
3341 # skip the file if uploads disabled
3342 if ($DISABLE_UPLOADS) {
3343 while (defined($data = $buffer->read)) { }
3347 # set the filename to some recognizable value
3348 if ( ( !defined($filename) || $filename eq '' ) && $multipart ) {
3349 $filename = "multipart/mixed";
3352 # choose a relatively unpredictable tmpfile sequence number
3353 my $seqno = unpack("%16C*",join('',localtime,grep {defined $_} values %ENV));
3354 for (my $cnt=10;$cnt>0;$cnt--) {
3355 next unless $tmpfile = new CGITempFile($seqno);
3356 $tmp = $tmpfile->as_string;
3357 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
3358 $seqno += int rand(100);
3360 die "CGI open of tmpfile: $!\n" unless defined $filehandle;
3361 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode
3362 && defined fileno($filehandle);
3364 # if this is an multipart/mixed attachment, save the header
3365 # together with the body for later parsing with an external
3366 # MIME parser module
3368 foreach ( keys %header ) {
3369 print $filehandle "$_: $header{$_}${CRLF}";
3371 print $filehandle "${CRLF}";
3377 while (defined($data = $buffer->read)) {
3378 if (defined $self->{'.upload_hook'})
3380 $totalbytes += length($data);
3381 &{$self->{'.upload_hook'}}($filename ,$data, $totalbytes, $self->{'.upload_data'});
3383 print $filehandle $data;
3386 # back up to beginning of file
3387 seek($filehandle,0,0);
3389 ## Close the filehandle if requested this allows a multipart MIME
3390 ## upload to contain many files, and we won't die due to too many
3391 ## open file handles. The user can access the files using the hash
3393 close $filehandle if $CLOSE_UPLOAD_FILES;
3394 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3396 # Save some information about the uploaded file where we can get
3398 # Use the typeglob as the key, as this is guaranteed to be
3399 # unique for each filehandle. Don't use the file descriptor as
3400 # this will be re-used for each filehandle if the
3401 # close_upload_files feature is used.
3402 $self->{'.tmpfiles'}->{$$filehandle}= {
3403 hndl => $filehandle,
3407 push(@{$self->{$param}},$filehandle);
3413 'upload' =><<'END_OF_FUNC',
3415 my($self,$param_name) = self_or_default(@_);
3416 my @param = grep(ref && fileno($_), $self->param($param_name));
3417 return unless @param;
3418 return wantarray ? @param : $param[0];
3422 'tmpFileName' => <<'END_OF_FUNC',
3424 my($self,$filename) = self_or_default(@_);
3425 return $self->{'.tmpfiles'}->{$$filename}->{name} ?
3426 $self->{'.tmpfiles'}->{$$filename}->{name}->as_string
3431 'uploadInfo' => <<'END_OF_FUNC',
3433 my($self,$filename) = self_or_default(@_);
3434 return $self->{'.tmpfiles'}->{$$filename}->{info};
3438 # internal routine, don't use
3439 '_set_values_and_labels' => <<'END_OF_FUNC',
3440 sub _set_values_and_labels {
3443 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
3444 return $self->param($n) if !defined($v);
3445 return $v if !ref($v);
3446 return ref($v) eq 'HASH' ? keys %$v : @$v;
3450 # internal routine, don't use
3451 '_set_attributes' => <<'END_OF_FUNC',
3452 sub _set_attributes {
3454 my($element, $attributes) = @_;
3455 return '' unless defined($attributes->{$element});
3457 foreach my $attrib (keys %{$attributes->{$element}}) {
3458 (my $clean_attrib = $attrib) =~ s/^-//;
3459 $attribs .= "@{[lc($clean_attrib)]}=\"$attributes->{$element}{$attrib}\" ";
3466 '_compile_all' => <<'END_OF_FUNC',
3469 next if defined(&$_);
3470 $AUTOLOAD = "CGI::$_";
3480 #########################################################
3481 # Globals and stubs for other packages that we use.
3482 #########################################################
3484 ################### Fh -- lightweight filehandle ###############
3493 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3500 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3501 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3503 'asString' => <<'END_OF_FUNC',
3506 # get rid of package name
3507 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
3508 $i =~ s/%(..)/ chr(hex($1)) /eg;
3509 return $i.$CGI::TAINTED;
3511 # This was an extremely clever patch that allowed "use strict refs".
3512 # Unfortunately it relied on another bug that caused leaky file descriptors.
3513 # The underlying bug has been fixed, so this no longer works. However
3514 # "strict refs" still works for some reason.
3516 # return ${*{$self}{SCALAR}};
3521 'compare' => <<'END_OF_FUNC',
3525 return "$self" cmp $value;
3529 'new' => <<'END_OF_FUNC',
3531 my($pack,$name,$file,$delete) = @_;
3532 _setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
3533 require Fcntl unless defined &Fcntl::O_RDWR;
3534 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3535 my $fv = ++$FH . $safename;
3536 my $ref = \*{"Fh::$fv"};
3537 $file =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3539 sysopen($ref,$safe,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3540 unlink($safe) if $delete;
3541 CORE::delete $Fh::{$fv};
3542 return bless $ref,$pack;
3549 ######################## MultipartBuffer ####################
3550 package MultipartBuffer;
3552 use constant DEBUG => 0;
3554 # how many bytes to read at a time. We use
3555 # a 4K buffer by default.
3556 $INITIAL_FILLUNIT = 1024 * 4;
3557 $TIMEOUT = 240*60; # 4 hour timeout for big files
3558 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3561 #reuse the autoload function
3562 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3564 # avoid autoloader warnings
3567 ###############################################################################
3568 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3569 ###############################################################################
3570 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3571 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3574 'new' => <<'END_OF_FUNC',
3576 my($package,$interface,$boundary,$length) = @_;
3577 $FILLUNIT = $INITIAL_FILLUNIT;
3578 $CGI::DefaultClass->binmode($IN); # if $CGI::needs_binmode; # just do it always
3580 # If the user types garbage into the file upload field,
3581 # then Netscape passes NOTHING to the server (not good).
3582 # We may hang on this read in that case. So we implement
3583 # a read timeout. If nothing is ready to read
3584 # by then, we return.
3586 # Netscape seems to be a little bit unreliable
3587 # about providing boundary strings.
3588 my $boundary_read = 0;
3591 # Under the MIME spec, the boundary consists of the
3592 # characters "--" PLUS the Boundary string
3594 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3595 # the two extra hyphens. We do a special case here on the user-agent!!!!
3596 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac|DreamPassport');
3598 } else { # otherwise we find it ourselves
3600 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3601 $boundary = <STDIN>; # BUG: This won't work correctly under mod_perl
3602 $length -= length($boundary);
3603 chomp($boundary); # remove the CRLF
3604 $/ = $old; # restore old line separator
3608 my $self = {LENGTH=>$length,
3609 CHUNKED=>!defined $length,
3610 BOUNDARY=>$boundary,
3611 INTERFACE=>$interface,
3615 $FILLUNIT = length($boundary)
3616 if length($boundary) > $FILLUNIT;
3618 my $retval = bless $self,ref $package || $package;
3620 # Read the preamble and the topmost (boundary) line plus the CRLF.
3621 unless ($boundary_read) {
3622 while ($self->read(0)) { }
3624 die "Malformed multipart POST: data truncated\n" if $self->eof;
3630 'readHeader' => <<'END_OF_FUNC',
3637 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS' || $CGI::EBCDIC;
3640 $self->fillBuffer($FILLUNIT);
3641 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3642 $ok++ if $self->{BUFFER} eq '';
3643 $bad++ if !$ok && $self->{LENGTH} <= 0;
3644 # this was a bad idea
3645 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3646 } until $ok || $bad;
3649 #EBCDIC NOTE: translate header into EBCDIC, but watch out for continuation lines!
3651 my($header) = substr($self->{BUFFER},0,$end+2);
3652 substr($self->{BUFFER},0,$end+4) = '';
3656 warn "untranslated header=$header\n" if DEBUG;
3657 $header = CGI::Util::ascii2ebcdic($header);
3658 warn "translated header=$header\n" if DEBUG;
3661 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3662 # (Folding Long Header Fields), 3.4.3 (Comments)
3663 # and 3.4.5 (Quoted-Strings).
3665 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3666 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3668 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3669 my ($field_name,$field_value) = ($1,$2);
3670 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3671 $return{$field_name}=$field_value;
3677 # This reads and returns the body as a single scalar value.
3678 'readBody' => <<'END_OF_FUNC',
3684 #EBCDIC NOTE: want to translate returnval into EBCDIC HERE
3686 while (defined($data = $self->read)) {
3687 $returnval .= $data;
3691 warn "untranslated body=$returnval\n" if DEBUG;
3692 $returnval = CGI::Util::ascii2ebcdic($returnval);
3693 warn "translated body=$returnval\n" if DEBUG;
3699 # This will read $bytes or until the boundary is hit, whichever happens
3700 # first. After the boundary is hit, we return undef. The next read will
3701 # skip over the boundary and begin reading again;
3702 'read' => <<'END_OF_FUNC',
3704 my($self,$bytes) = @_;
3706 # default number of bytes to read
3707 $bytes = $bytes || $FILLUNIT;
3709 # Fill up our internal buffer in such a way that the boundary
3710 # is never split between reads.
3711 $self->fillBuffer($bytes);
3713 my $boundary_start = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}) : $self->{BOUNDARY};
3714 my $boundary_end = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}.'--') : $self->{BOUNDARY}.'--';
3716 # Find the boundary in the buffer (it may not be there).
3717 my $start = index($self->{BUFFER},$boundary_start);
3719 warn "boundary=$self->{BOUNDARY} length=$self->{LENGTH} start=$start\n" if DEBUG;
3721 # protect against malformed multipart POST operations
3722 die "Malformed multipart POST\n" unless $self->{CHUNKED} || ($start >= 0 || $self->{LENGTH} > 0);
3724 #EBCDIC NOTE: want to translate boundary search into ASCII here.
3726 # If the boundary begins the data, then skip past it
3730 # clear us out completely if we've hit the last boundary.
3731 if (index($self->{BUFFER},$boundary_end)==0) {
3737 # just remove the boundary.
3738 substr($self->{BUFFER},0,length($boundary_start))='';
3739 $self->{BUFFER} =~ s/^\012\015?//;
3744 if ($start > 0) { # read up to the boundary
3745 $bytesToReturn = $start-2 > $bytes ? $bytes : $start;
3746 } else { # read the requested number of bytes
3747 # leave enough bytes in the buffer to allow us to read
3748 # the boundary. Thanks to Kevin Hendrick for finding
3750 $bytesToReturn = $bytes - (length($boundary_start)+1);
3753 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3754 substr($self->{BUFFER},0,$bytesToReturn)='';
3756 # If we hit the boundary, remove the CRLF from the end.
3757 return ($bytesToReturn==$start)
3758 ? substr($returnval,0,-2) : $returnval;
3763 # This fills up our internal buffer in such a way that the
3764 # boundary is never split between reads
3765 'fillBuffer' => <<'END_OF_FUNC',
3767 my($self,$bytes) = @_;
3768 return unless $self->{CHUNKED} || $self->{LENGTH};
3770 my($boundaryLength) = length($self->{BOUNDARY});
3771 my($bufferLength) = length($self->{BUFFER});
3772 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3773 $bytesToRead = $self->{LENGTH} if !$self->{CHUNKED} && $self->{LENGTH} < $bytesToRead;
3775 # Try to read some data. We may hang here if the browser is screwed up.
3776 my $bytesRead = $self->{INTERFACE}->read_from_client(\$self->{BUFFER},
3779 warn "bytesToRead=$bytesToRead, bufferLength=$bufferLength, buffer=$self->{BUFFER}\n" if DEBUG;
3780 $self->{BUFFER} = '' unless defined $self->{BUFFER};
3782 # An apparent bug in the Apache server causes the read()
3783 # to return zero bytes repeatedly without blocking if the
3784 # remote user aborts during a file transfer. I don't know how
3785 # they manage this, but the workaround is to abort if we get
3786 # more than SPIN_LOOP_MAX consecutive zero reads.
3787 if ($bytesRead <= 0) {
3788 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3789 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3791 $self->{ZERO_LOOP_COUNTER}=0;
3794 $self->{LENGTH} -= $bytesRead if !$self->{CHUNKED} && $bytesRead;
3799 # Return true when we've finished reading
3800 'eof' => <<'END_OF_FUNC'
3803 return 1 if (length($self->{BUFFER}) == 0)
3804 && ($self->{LENGTH} <= 0);
3812 ####################################################################################
3813 ################################## TEMPORARY FILES #################################
3814 ####################################################################################
3815 package CGITempFile;
3819 $MAC = $CGI::OS eq 'MACINTOSH';
3820 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3821 unless (defined $TMPDIRECTORY) {
3822 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3823 "C:${SL}temp","${SL}tmp","${SL}temp",
3824 "${vol}${SL}Temporary Items",
3825 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3826 "C:${SL}system${SL}temp");
3827 unshift(@TEMP,$ENV{'TMPDIR'}) if defined $ENV{'TMPDIR'};
3829 # this feature was supposed to provide per-user tmpfiles, but
3830 # it is problematic.
3831 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3832 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3833 # : can generate a 'getpwuid() not implemented' exception, even though
3834 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3835 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3836 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3839 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3842 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3849 # cute feature, but overload implementation broke it
3850 # %OVERLOAD = ('""'=>'as_string');
3851 *CGITempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3855 $$self =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3856 my $safe = $1; # untaint operation
3857 unlink $safe; # get rid of the file
3860 ###############################################################################
3861 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3862 ###############################################################################
3863 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3864 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3867 'new' => <<'END_OF_FUNC',
3869 my($package,$sequence) = @_;
3871 find_tempdir() unless -w $TMPDIRECTORY;
3872 for (my $i = 0; $i < $MAXTRIES; $i++) {
3873 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3875 # check that it is a more-or-less valid filename
3876 return unless $filename =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$!;
3877 # this used to untaint, now it doesn't
3879 return bless \$filename;
3883 'as_string' => <<'END_OF_FUNC'
3895 # We get a whole bunch of warnings about "possibly uninitialized variables"
3896 # when running with the -w switch. Touch them all once to get rid of the
3897 # warnings. This is ugly and I hate it.
3902 $MultipartBuffer::SPIN_LOOP_MAX;
3903 $MultipartBuffer::CRLF;
3904 $MultipartBuffer::TIMEOUT;
3905 $MultipartBuffer::INITIAL_FILLUNIT;
3916 CGI - Simple Common Gateway Interface Class
3920 # CGI script that creates a fill-out form
3921 # and echoes back its values.
3923 use CGI qw/:standard/;
3925 start_html('A Simple Example'),
3926 h1('A Simple Example'),
3928 "What's your name? ",textfield('name'),p,
3929 "What's the combination?", p,
3930 checkbox_group(-name=>'words',
3931 -values=>['eenie','meenie','minie','moe'],
3932 -defaults=>['eenie','minie']), p,
3933 "What's your favorite color? ",
3934 popup_menu(-name=>'color',
3935 -values=>['red','green','blue','chartreuse']),p,
3941 my $name = param('name');
3942 my $keywords = join ', ',param('words');
3943 my $color = param('color');
3944 print "Your name is",em(escapeHTML($name)),p,
3945 "The keywords are: ",em(escapeHTML($keywords)),p,
3946 "Your favorite color is ",em(escapeHTML($color)),
3952 This perl library uses perl5 objects to make it easy to create Web
3953 fill-out forms and parse their contents. This package defines CGI
3954 objects, entities that contain the values of the current query string
3955 and other state variables. Using a CGI object's methods, you can
3956 examine keywords and parameters passed to your script, and create
3957 forms whose initial values are taken from the current query (thereby
3958 preserving state information). The module provides shortcut functions
3959 that produce boilerplate HTML, reducing typing and coding errors. It
3960 also provides functionality for some of the more advanced features of
3961 CGI scripting, including support for file uploads, cookies, cascading
3962 style sheets, server push, and frames.
3964 CGI.pm also provides a simple function-oriented programming style for
3965 those who don't need its object-oriented features.
3967 The current version of CGI.pm is available at
3969 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3970 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3974 =head2 PROGRAMMING STYLE
3976 There are two styles of programming with CGI.pm, an object-oriented
3977 style and a function-oriented style. In the object-oriented style you
3978 create one or more CGI objects and then use object methods to create
3979 the various elements of the page. Each CGI object starts out with the
3980 list of named parameters that were passed to your CGI script by the
3981 server. You can modify the objects, save them to a file or database
3982 and recreate them. Because each object corresponds to the "state" of
3983 the CGI script, and because each object's parameter list is
3984 independent of the others, this allows you to save the state of the
3985 script and restore it later.
3987 For example, using the object oriented style, here is how you create
3988 a simple "Hello World" HTML page:
3990 #!/usr/local/bin/perl -w
3991 use CGI; # load CGI routines
3992 $q = new CGI; # create new CGI object
3993 print $q->header, # create the HTTP header
3994 $q->start_html('hello world'), # start the HTML
3995 $q->h1('hello world'), # level 1 header
3996 $q->end_html; # end the HTML
3998 In the function-oriented style, there is one default CGI object that
3999 you rarely deal with directly. Instead you just call functions to
4000 retrieve CGI parameters, create HTML tags, manage cookies, and so
4001 on. This provides you with a cleaner programming interface, but
4002 limits you to using one CGI object at a time. The following example
4003 prints the same page, but uses the function-oriented interface.
4004 The main differences are that we now need to import a set of functions
4005 into our name space (usually the "standard" functions), and we don't
4006 need to create the CGI object.
4008 #!/usr/local/bin/perl
4009 use CGI qw/:standard/; # load standard CGI routines
4010 print header, # create the HTTP header
4011 start_html('hello world'), # start the HTML
4012 h1('hello world'), # level 1 header
4013 end_html; # end the HTML
4015 The examples in this document mainly use the object-oriented style.
4016 See HOW TO IMPORT FUNCTIONS for important information on
4017 function-oriented programming in CGI.pm
4019 =head2 CALLING CGI.PM ROUTINES
4021 Most CGI.pm routines accept several arguments, sometimes as many as 20
4022 optional ones! To simplify this interface, all routines use a named
4023 argument calling style that looks like this:
4025 print $q->header(-type=>'image/gif',-expires=>'+3d');
4027 Each argument name is preceded by a dash. Neither case nor order
4028 matters in the argument list. -type, -Type, and -TYPE are all
4029 acceptable. In fact, only the first argument needs to begin with a
4030 dash. If a dash is present in the first argument, CGI.pm assumes
4031 dashes for the subsequent ones.
4033 Several routines are commonly called with just one argument. In the
4034 case of these routines you can provide the single argument without an
4035 argument name. header() happens to be one of these routines. In this
4036 case, the single argument is the document type.
4038 print $q->header('text/html');
4040 Other such routines are documented below.
4042 Sometimes named arguments expect a scalar, sometimes a reference to an
4043 array, and sometimes a reference to a hash. Often, you can pass any
4044 type of argument and the routine will do whatever is most appropriate.
4045 For example, the param() routine is used to set a CGI parameter to a
4046 single or a multi-valued value. The two cases are shown below:
4048 $q->param(-name=>'veggie',-value=>'tomato');
4049 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
4051 A large number of routines in CGI.pm actually aren't specifically
4052 defined in the module, but are generated automatically as needed.
4053 These are the "HTML shortcuts," routines that generate HTML tags for
4054 use in dynamically-generated pages. HTML tags have both attributes
4055 (the attribute="value" pairs within the tag itself) and contents (the
4056 part between the opening and closing pairs.) To distinguish between
4057 attributes and contents, CGI.pm uses the convention of passing HTML
4058 attributes as a hash reference as the first argument, and the
4059 contents, if any, as any subsequent arguments. It works out like
4065 h1('some','contents'); <h1>some contents</h1>
4066 h1({-align=>left}); <h1 align="LEFT">
4067 h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
4069 HTML tags are described in more detail later.
4071 Many newcomers to CGI.pm are puzzled by the difference between the
4072 calling conventions for the HTML shortcuts, which require curly braces
4073 around the HTML tag attributes, and the calling conventions for other
4074 routines, which manage to generate attributes without the curly
4075 brackets. Don't be confused. As a convenience the curly braces are
4076 optional in all but the HTML shortcuts. If you like, you can use
4077 curly braces when calling any routine that takes named arguments. For
4080 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
4082 If you use the B<-w> switch, you will be warned that some CGI.pm argument
4083 names conflict with built-in Perl functions. The most frequent of
4084 these is the -values argument, used to create multi-valued menus,
4085 radio button clusters and the like. To get around this warning, you
4086 have several choices:
4092 Use another name for the argument, if one is available.
4093 For example, -value is an alias for -values.
4097 Change the capitalization, e.g. -Values
4101 Put quotes around the argument name, e.g. '-values'
4105 Many routines will do something useful with a named argument that it
4106 doesn't recognize. For example, you can produce non-standard HTTP
4107 header fields by providing them as named arguments:
4109 print $q->header(-type => 'text/html',
4110 -cost => 'Three smackers',
4111 -annoyance_level => 'high',
4112 -complaints_to => 'bit bucket');
4114 This will produce the following nonstandard HTTP header:
4117 Cost: Three smackers
4118 Annoyance-level: high
4119 Complaints-to: bit bucket
4120 Content-type: text/html
4122 Notice the way that underscores are translated automatically into
4123 hyphens. HTML-generating routines perform a different type of
4126 This feature allows you to keep up with the rapidly changing HTTP and
4129 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
4133 This will parse the input (from both POST and GET methods) and store
4134 it into a perl5 object called $query.
4136 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
4138 $query = new CGI(INPUTFILE);
4140 If you provide a file handle to the new() method, it will read
4141 parameters from the file (or STDIN, or whatever). The file can be in
4142 any of the forms describing below under debugging (i.e. a series of
4143 newline delimited TAG=VALUE pairs will work). Conveniently, this type
4144 of file is created by the save() method (see below). Multiple records
4145 can be saved and restored.
4147 Perl purists will be pleased to know that this syntax accepts
4148 references to file handles, or even references to filehandle globs,
4149 which is the "official" way to pass a filehandle:
4151 $query = new CGI(\*STDIN);
4153 You can also initialize the CGI object with a FileHandle or IO::File
4156 If you are using the function-oriented interface and want to
4157 initialize CGI state from a file handle, the way to do this is with
4158 B<restore_parameters()>. This will (re)initialize the
4159 default CGI object from the indicated file handle.
4161 open (IN,"test.in") || die;
4162 restore_parameters(IN);
4165 You can also initialize the query object from an associative array
4168 $query = new CGI( {'dinosaur'=>'barney',
4169 'song'=>'I love you',
4170 'friends'=>[qw/Jessica George Nancy/]}
4173 or from a properly formatted, URL-escaped query string:
4175 $query = new CGI('dinosaur=barney&color=purple');
4177 or from a previously existing CGI object (currently this clones the
4178 parameter list, but none of the other object-specific fields, such as
4181 $old_query = new CGI;
4182 $new_query = new CGI($old_query);
4184 To create an empty query, initialize it from an empty string or hash:
4186 $empty_query = new CGI("");
4190 $empty_query = new CGI({});
4192 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
4194 @keywords = $query->keywords
4196 If the script was invoked as the result of an <ISINDEX> search, the
4197 parsed keywords can be obtained as an array using the keywords() method.
4199 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
4201 @names = $query->param
4203 If the script was invoked with a parameter list
4204 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
4205 will return the parameter names as a list. If the script was invoked
4206 as an <ISINDEX> script and contains a string without ampersands
4207 (e.g. "value1+value2+value3") , there will be a single parameter named
4208 "keywords" containing the "+"-delimited keywords.
4210 NOTE: As of version 1.5, the array of parameter names returned will
4211 be in the same order as they were submitted by the browser.
4212 Usually this order is the same as the order in which the
4213 parameters are defined in the form (however, this isn't part
4214 of the spec, and so isn't guaranteed).
4216 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
4218 @values = $query->param('foo');
4222 $value = $query->param('foo');
4224 Pass the param() method a single argument to fetch the value of the
4225 named parameter. If the parameter is multivalued (e.g. from multiple
4226 selections in a scrolling list), you can ask to receive an array. Otherwise
4227 the method will return a single value.
4229 If a value is not given in the query string, as in the queries
4230 "name1=&name2=" or "name1&name2", it will be returned as an empty
4231 string. This feature is new in 2.63.
4234 If the parameter does not exist at all, then param() will return undef
4235 in a scalar context, and the empty list in a list context.
4238 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
4240 $query->param('foo','an','array','of','values');
4242 This sets the value for the named parameter 'foo' to an array of
4243 values. This is one way to change the value of a field AFTER
4244 the script has been invoked once before. (Another way is with
4245 the -override parameter accepted by all methods that generate
4248 param() also recognizes a named parameter style of calling described
4249 in more detail later:
4251 $query->param(-name=>'foo',-values=>['an','array','of','values']);
4255 $query->param(-name=>'foo',-value=>'the value');
4257 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
4259 $query->append(-name=>'foo',-values=>['yet','more','values']);
4261 This adds a value or list of values to the named parameter. The
4262 values are appended to the end of the parameter if it already exists.
4263 Otherwise the parameter is created. Note that this method only
4264 recognizes the named argument calling syntax.
4266 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
4268 $query->import_names('R');
4270 This creates a series of variables in the 'R' namespace. For example,
4271 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
4272 If no namespace is given, this method will assume 'Q'.
4273 WARNING: don't import anything into 'main'; this is a major security
4276 NOTE 1: Variable names are transformed as necessary into legal Perl
4277 variable names. All non-legal characters are transformed into
4278 underscores. If you need to keep the original names, you should use
4279 the param() method instead to access CGI variables by name.
4281 NOTE 2: In older versions, this method was called B<import()>. As of version 2.20,
4282 this name has been removed completely to avoid conflict with the built-in
4283 Perl module B<import> operator.
4285 =head2 DELETING A PARAMETER COMPLETELY:
4287 $query->delete('foo','bar','baz');
4289 This completely clears a list of parameters. It sometimes useful for
4290 resetting parameters that you don't want passed down between script
4293 If you are using the function call interface, use "Delete()" instead
4294 to avoid conflicts with Perl's built-in delete operator.
4296 =head2 DELETING ALL PARAMETERS:
4298 $query->delete_all();
4300 This clears the CGI object completely. It might be useful to ensure
4301 that all the defaults are taken when you create a fill-out form.
4303 Use Delete_all() instead if you are using the function call interface.
4305 =head2 HANDLING NON-URLENCODED ARGUMENTS
4308 If POSTed data is not of type application/x-www-form-urlencoded or
4309 multipart/form-data, then the POSTed data will not be processed, but
4310 instead be returned as-is in a parameter named POSTDATA. To retrieve
4311 it, use code like this:
4313 my $data = $query->param('POSTDATA');
4315 (If you don't know what the preceding means, don't worry about it. It
4316 only affects people trying to use CGI for XML processing and other
4320 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
4322 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
4323 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
4325 If you need access to the parameter list in a way that isn't covered
4326 by the methods above, you can obtain a direct reference to it by
4327 calling the B<param_fetch()> method with the name of the . This
4328 will return an array reference to the named parameters, which you then
4329 can manipulate in any way you like.
4331 You can also use a named argument style using the B<-name> argument.
4333 =head2 FETCHING THE PARAMETER LIST AS A HASH:
4336 print $params->{'address'};
4337 @foo = split("\0",$params->{'foo'});
4343 Many people want to fetch the entire parameter list as a hash in which
4344 the keys are the names of the CGI parameters, and the values are the
4345 parameters' values. The Vars() method does this. Called in a scalar
4346 context, it returns the parameter list as a tied hash reference.
4347 Changing a key changes the value of the parameter in the underlying
4348 CGI parameter list. Called in a list context, it returns the
4349 parameter list as an ordinary hash. This allows you to read the
4350 contents of the parameter list, but not to change it.
4352 When using this, the thing you must watch out for are multivalued CGI
4353 parameters. Because a hash cannot distinguish between scalar and
4354 list context, multivalued parameters will be returned as a packed
4355 string, separated by the "\0" (null) character. You must split this
4356 packed string in order to get at the individual values. This is the
4357 convention introduced long ago by Steve Brenner in his cgi-lib.pl
4358 module for Perl version 4.
4360 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
4361 function calls (also see the section on CGI-LIB compatibility).
4363 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
4365 $query->save(\*FILEHANDLE)
4367 This will write the current state of the form to the provided
4368 filehandle. You can read it back in by providing a filehandle
4369 to the new() method. Note that the filehandle can be a file, a pipe,
4372 The format of the saved file is:
4380 Both name and value are URL escaped. Multi-valued CGI parameters are
4381 represented as repeated names. A session record is delimited by a
4382 single = symbol. You can write out multiple records and read them
4383 back in with several calls to B<new>. You can do this across several
4384 sessions by opening the file in append mode, allowing you to create
4385 primitive guest books, or to keep a history of users' queries. Here's
4386 a short example of creating multiple session records:
4390 open (OUT,">>test.out") || die;
4392 foreach (0..$records) {
4394 $q->param(-name=>'counter',-value=>$_);
4399 # reopen for reading
4400 open (IN,"test.out") || die;
4402 my $q = new CGI(\*IN);
4403 print $q->param('counter'),"\n";
4406 The file format used for save/restore is identical to that used by the
4407 Whitehead Genome Center's data exchange format "Boulderio", and can be
4408 manipulated and even databased using Boulderio utilities. See
4410 http://stein.cshl.org/boulder/
4412 for further details.
4414 If you wish to use this method from the function-oriented (non-OO)
4415 interface, the exported name for this method is B<save_parameters()>.
4417 =head2 RETRIEVING CGI ERRORS
4419 Errors can occur while processing user input, particularly when
4420 processing uploaded files. When these errors occur, CGI will stop
4421 processing and return an empty parameter list. You can test for
4422 the existence and nature of errors using the I<cgi_error()> function.
4423 The error messages are formatted as HTTP status codes. You can either
4424 incorporate the error text into an HTML page, or use it as the value
4427 my $error = $q->cgi_error;
4429 print $q->header(-status=>$error),
4430 $q->start_html('Problems'),
4431 $q->h2('Request not processed'),
4436 When using the function-oriented interface (see the next section),
4437 errors may only occur the first time you call I<param()>. Be ready
4440 =head2 USING THE FUNCTION-ORIENTED INTERFACE
4442 To use the function-oriented interface, you must specify which CGI.pm
4443 routines or sets of routines to import into your script's namespace.
4444 There is a small overhead associated with this importation, but it
4447 use CGI <list of methods>;
4449 The listed methods will be imported into the current package; you can
4450 call them directly without creating a CGI object first. This example
4451 shows how to import the B<param()> and B<header()>
4452 methods, and then use them directly:
4454 use CGI 'param','header';
4455 print header('text/plain');
4456 $zipcode = param('zipcode');
4458 More frequently, you'll import common sets of functions by referring
4459 to the groups by name. All function sets are preceded with a ":"
4460 character as in ":html3" (for tags defined in the HTML 3 standard).
4462 Here is a list of the function sets you can import:
4468 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4473 Import all fill-out form generating methods, such as B<textfield()>.
4477 Import all methods that generate HTML 2.0 standard elements.
4481 Import all methods that generate HTML 3.0 elements (such as
4482 <table>, <super> and <sub>).
4486 Import all methods that generate HTML 4 elements (such as
4487 <abbrev>, <acronym> and <thead>).
4491 Import all methods that generate Netscape-specific HTML extensions.
4495 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4500 Import "standard" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.
4504 Import all the available methods. For the full list, see the CGI.pm
4505 code, where the variable %EXPORT_TAGS is defined.
4509 If you import a function name that is not part of CGI.pm, the module
4510 will treat it as a new HTML tag and generate the appropriate
4511 subroutine. You can then use it like any other HTML tag. This is to
4512 provide for the rapidly-evolving HTML "standard." For example, say
4513 Microsoft comes out with a new tag called <gradient> (which causes the
4514 user's desktop to be flooded with a rotating gradient fill until his
4515 machine reboots). You don't need to wait for a new version of CGI.pm
4516 to start using it immediately:
4518 use CGI qw/:standard :html3 gradient/;
4519 print gradient({-start=>'red',-end=>'blue'});
4521 Note that in the interests of execution speed CGI.pm does B<not> use
4522 the standard L<Exporter> syntax for specifying load symbols. This may
4523 change in the future.
4525 If you import any of the state-maintaining CGI or form-generating
4526 methods, a default CGI object will be created and initialized
4527 automatically the first time you use any of the methods that require
4528 one to be present. This includes B<param()>, B<textfield()>,
4529 B<submit()> and the like. (If you need direct access to the CGI
4530 object, you can find it in the global variable B<$CGI::Q>). By
4531 importing CGI.pm methods, you can create visually elegant scripts:
4533 use CGI qw/:standard/;
4536 start_html('Simple Script'),
4537 h1('Simple Script'),
4539 "What's your name? ",textfield('name'),p,
4540 "What's the combination?",
4541 checkbox_group(-name=>'words',
4542 -values=>['eenie','meenie','minie','moe'],
4543 -defaults=>['eenie','moe']),p,
4544 "What's your favorite color?",
4545 popup_menu(-name=>'color',
4546 -values=>['red','green','blue','chartreuse']),p,
4553 "Your name is ",em(param('name')),p,
4554 "The keywords are: ",em(join(", ",param('words'))),p,
4555 "Your favorite color is ",em(param('color')),".\n";
4561 In addition to the function sets, there are a number of pragmas that
4562 you can import. Pragmas, which are always preceded by a hyphen,
4563 change the way that CGI.pm functions in various ways. Pragmas,
4564 function sets, and individual functions can all be imported in the
4565 same use() line. For example, the following use statement imports the
4566 standard set of functions and enables debugging mode (pragma
4569 use CGI qw/:standard -debug/;
4571 The current list of pragmas is as follows:
4577 When you I<use CGI -any>, then any method that the query object
4578 doesn't recognize will be interpreted as a new HTML tag. This allows
4579 you to support the next I<ad hoc> Netscape or Microsoft HTML
4580 extension. This lets you go wild with new and unsupported tags:
4584 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4586 Since using <cite>any</cite> causes any mistyped method name
4587 to be interpreted as an HTML tag, use it with care or not at
4592 This causes the indicated autoloaded methods to be compiled up front,
4593 rather than deferred to later. This is useful for scripts that run
4594 for an extended period of time under FastCGI or mod_perl, and for
4595 those destined to be crunched by Malcom Beattie's Perl compiler. Use
4596 it in conjunction with the methods or method families you plan to use.
4598 use CGI qw(-compile :standard :html3);
4602 use CGI qw(-compile :all);
4604 Note that using the -compile pragma in this way will always have
4605 the effect of importing the compiled functions into the current
4606 namespace. If you want to compile without importing use the
4607 compile() method instead:
4612 This is particularly useful in a mod_perl environment, in which you
4613 might want to precompile all CGI routines in a startup script, and
4614 then import the functions individually in each mod_perl script.
4618 By default the CGI module implements a state-preserving behavior
4619 called "sticky" fields. The way this works is that if you are
4620 regenerating a form, the methods that generate the form field values
4621 will interrogate param() to see if similarly-named parameters are
4622 present in the query string. If they find a like-named parameter, they
4623 will use it to set their default values.
4625 Sometimes this isn't what you want. The B<-nosticky> pragma prevents
4626 this behavior. You can also selectively change the sticky behavior in
4627 each element that you generate.
4631 Automatically add tab index attributes to each form field. With this
4632 option turned off, you can still add tab indexes manually by passing a
4633 -tabindex option to each field-generating method.
4635 =item -no_undef_params
4637 This keeps CGI.pm from including undef params in the parameter list.
4641 By default, CGI.pm versions 2.69 and higher emit XHTML
4642 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4643 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4646 If start_html()'s -dtd parameter specifies an HTML 2.0 or 3.2 DTD,
4647 XHTML will automatically be disabled without needing to use this
4652 This makes CGI.pm produce a header appropriate for an NPH (no
4653 parsed header) script. You may need to do other things as well
4654 to tell the server that the script is NPH. See the discussion
4655 of NPH scripts below.
4657 =item -newstyle_urls
4659 Separate the name=value pairs in CGI parameter query strings with
4660 semicolons rather than ampersands. For example:
4662 ?name=fred;age=24;favorite_color=3
4664 Semicolon-delimited query strings are always accepted, but will not be
4665 emitted by self_url() and query_string() unless the -newstyle_urls
4666 pragma is specified.
4668 This became the default in version 2.64.
4670 =item -oldstyle_urls
4672 Separate the name=value pairs in CGI parameter query strings with
4673 ampersands rather than semicolons. This is no longer the default.
4677 This overrides the autoloader so that any function in your program
4678 that is not recognized is referred to CGI.pm for possible evaluation.
4679 This allows you to use all the CGI.pm functions without adding them to
4680 your symbol table, which is of concern for mod_perl users who are
4681 worried about memory consumption. I<Warning:> when
4682 I<-autoload> is in effect, you cannot use "poetry mode"
4683 (functions without the parenthesis). Use I<hr()> rather
4684 than I<hr>, or add something like I<use subs qw/hr p header/>
4685 to the top of your script.
4689 This turns off the command-line processing features. If you want to
4690 run a CGI.pm script from the command line to produce HTML, and you
4691 don't want it to read CGI parameters from the command line or STDIN,
4692 then use this pragma:
4694 use CGI qw(-no_debug :standard);
4698 This turns on full debugging. In addition to reading CGI arguments
4699 from the command-line processing, CGI.pm will pause and try to read
4700 arguments from STDIN, producing the message "(offline mode: enter
4701 name=value pairs on standard input)" features.
4703 See the section on debugging for more details.
4705 =item -private_tempfiles
4707 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4708 file to a temporary directory, then deletes the file when done.
4709 However, this opens the risk of eavesdropping as described in the file
4710 upload section. Another CGI script author could peek at this data
4711 during the upload, even if it is confidential information. On Unix
4712 systems, the -private_tempfiles pragma will cause the temporary file
4713 to be unlinked as soon as it is opened and before any data is written
4714 into it, reducing, but not eliminating the risk of eavesdropping
4715 (there is still a potential race condition). To make life harder for
4716 the attacker, the program chooses tempfile names by calculating a 32
4717 bit checksum of the incoming HTTP headers.
4719 To ensure that the temporary file cannot be read by other CGI scripts,
4720 use suEXEC or a CGI wrapper program to run your script. The temporary
4721 file is created with mode 0600 (neither world nor group readable).
4723 The temporary directory is selected using the following algorithm:
4725 1. if the current user (e.g. "nobody") has a directory named
4726 "tmp" in its home directory, use that (Unix systems only).
4728 2. if the environment variable TMPDIR exists, use the location
4731 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4732 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4734 Each of these locations is checked that it is a directory and is
4735 writable. If not, the algorithm tries the next choice.
4739 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4741 Many of the methods generate HTML tags. As described below, tag
4742 functions automatically generate both the opening and closing tags.
4745 print h1('Level 1 Header');
4749 <h1>Level 1 Header</h1>
4751 There will be some times when you want to produce the start and end
4752 tags yourself. In this case, you can use the form start_I<tag_name>
4753 and end_I<tag_name>, as in:
4755 print start_h1,'Level 1 Header',end_h1;
4757 With a few exceptions (described below), start_I<tag_name> and
4758 end_I<tag_name> functions are not generated automatically when you
4759 I<use CGI>. However, you can specify the tags you want to generate
4760 I<start/end> functions for by putting an asterisk in front of their
4761 name, or, alternatively, requesting either "start_I<tag_name>" or
4762 "end_I<tag_name>" in the import list.
4766 use CGI qw/:standard *table start_ul/;
4768 In this example, the following functions are generated in addition to
4773 =item 1. start_table() (generates a <table> tag)
4775 =item 2. end_table() (generates a </table> tag)
4777 =item 3. start_ul() (generates a <ul> tag)
4779 =item 4. end_ul() (generates a </ul> tag)
4783 =head1 GENERATING DYNAMIC DOCUMENTS
4785 Most of CGI.pm's functions deal with creating documents on the fly.
4786 Generally you will produce the HTTP header first, followed by the
4787 document itself. CGI.pm provides functions for generating HTTP
4788 headers of various types as well as for generating HTML. For creating
4789 GIF images, see the GD.pm module.
4791 Each of these functions produces a fragment of HTML or HTTP which you
4792 can print out directly so that it displays in the browser window,
4793 append to a string, or save to a file for later use.
4795 =head2 CREATING A STANDARD HTTP HEADER:
4797 Normally the first thing you will do in any CGI script is print out an
4798 HTTP header. This tells the browser what type of document to expect,
4799 and gives other optional information, such as the language, expiration
4800 date, and whether to cache the document. The header can also be
4801 manipulated for special purposes, such as server push and pay per view
4808 print header('image/gif');
4812 print header('text/html','204 No response');
4816 print header(-type=>'image/gif',
4818 -status=>'402 Payment required',
4822 -attachment=>'foo.gif',
4825 header() returns the Content-type: header. You can provide your own
4826 MIME type if you choose, otherwise it defaults to text/html. An
4827 optional second parameter specifies the status code and a human-readable
4828 message. For example, you can specify 204, "No response" to create a
4829 script that tells the browser to do nothing at all.
4831 The last example shows the named argument style for passing arguments
4832 to the CGI methods using named parameters. Recognized parameters are
4833 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
4834 parameters will be stripped of their initial hyphens and turned into
4835 header fields, allowing you to specify any HTTP header you desire.
4836 Internal underscores will be turned into hyphens:
4838 print header(-Content_length=>3002);
4840 Most browsers will not cache the output from CGI scripts. Every time
4841 the browser reloads the page, the script is invoked anew. You can
4842 change this behavior with the B<-expires> parameter. When you specify
4843 an absolute or relative expiration interval with this parameter, some
4844 browsers and proxy servers will cache the script's output until the
4845 indicated expiration date. The following forms are all valid for the
4848 +30s 30 seconds from now
4849 +10m ten minutes from now
4850 +1h one hour from now
4851 -1d yesterday (i.e. "ASAP!")
4854 +10y in ten years time
4855 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
4857 The B<-cookie> parameter generates a header that tells the browser to provide
4858 a "magic cookie" during all subsequent transactions with your script.
4859 Netscape cookies have a special format that includes interesting attributes
4860 such as expiration time. Use the cookie() method to create and retrieve
4863 The B<-nph> parameter, if set to a true value, will issue the correct
4864 headers to work with a NPH (no-parse-header) script. This is important
4865 to use with certain servers that expect all their scripts to be NPH.
4867 The B<-charset> parameter can be used to control the character set
4868 sent to the browser. If not provided, defaults to ISO-8859-1. As a
4869 side effect, this sets the charset() method as well.
4871 The B<-attachment> parameter can be used to turn the page into an
4872 attachment. Instead of displaying the page, some browsers will prompt
4873 the user to save it to disk. The value of the argument is the
4874 suggested name for the saved file. In order for this to work, you may
4875 have to set the B<-type> to "application/octet-stream".
4877 The B<-p3p> parameter will add a P3P tag to the outgoing header. The
4878 parameter can be an arrayref or a space-delimited string of P3P tags.
4881 print header(-p3p=>[qw(CAO DSP LAW CURa)]);
4882 print header(-p3p=>'CAO DSP LAW CURa');
4884 In either case, the outgoing header will be formatted as:
4886 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
4888 =head2 GENERATING A REDIRECTION HEADER
4890 print redirect('http://somewhere.else/in/movie/land');
4892 Sometimes you don't want to produce a document yourself, but simply
4893 redirect the browser elsewhere, perhaps choosing a URL based on the
4894 time of day or the identity of the user.
4896 The redirect() function redirects the browser to a different URL. If
4897 you use redirection like this, you should B<not> print out a header as
4900 You should always use full URLs (including the http: or ftp: part) in
4901 redirection requests. Relative URLs will not work correctly.
4903 You can also use named arguments:
4905 print redirect(-uri=>'http://somewhere.else/in/movie/land',
4909 The B<-nph> parameter, if set to a true value, will issue the correct
4910 headers to work with a NPH (no-parse-header) script. This is important
4911 to use with certain servers, such as Microsoft IIS, which
4912 expect all their scripts to be NPH.
4914 The B<-status> parameter will set the status of the redirect. HTTP
4915 defines three different possible redirection status codes:
4917 301 Moved Permanently
4921 The default if not specified is 302, which means "moved temporarily."
4922 You may change the status to another status code if you wish. Be
4923 advised that changing the status to anything other than 301, 302 or
4924 303 will probably break redirection.
4926 =head2 CREATING THE HTML DOCUMENT HEADER
4928 print start_html(-title=>'Secrets of the Pyramids',
4929 -author=>'fred@capricorn.org',
4932 -meta=>{'keywords'=>'pharaoh secret mummy',
4933 'copyright'=>'copyright 1996 King Tut'},
4934 -style=>{'src'=>'/styles/style1.css'},
4937 After creating the HTTP header, most CGI scripts will start writing
4938 out an HTML document. The start_html() routine creates the top of the
4939 page, along with a lot of optional information that controls the
4940 page's appearance and behavior.
4942 This method returns a canned HTML header and the opening <body> tag.
4943 All parameters are optional. In the named parameter form, recognized
4944 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4945 (see below for the explanation). Any additional parameters you
4946 provide, such as the Netscape unofficial BGCOLOR attribute, are added
4947 to the <body> tag. Additional parameters must be proceeded by a
4950 The argument B<-xbase> allows you to provide an HREF for the <base> tag
4951 different from the current location, as in
4953 -xbase=>"http://home.mcom.com/"
4955 All relative links will be interpreted relative to this tag.
4957 The argument B<-target> allows you to provide a default target frame
4958 for all the links and fill-out forms on the page. B<This is a
4959 non-standard HTTP feature which only works with Netscape browsers!>
4960 See the Netscape documentation on frames for details of how to
4963 -target=>"answer_window"
4965 All relative links will be interpreted relative to this tag.
4966 You add arbitrary meta information to the header with the B<-meta>
4967 argument. This argument expects a reference to an associative array
4968 containing name/value pairs of meta information. These will be turned
4969 into a series of header <meta> tags that look something like this:
4971 <meta name="keywords" content="pharaoh secret mummy">
4972 <meta name="description" content="copyright 1996 King Tut">
4974 To create an HTTP-EQUIV type of <meta> tag, use B<-head>, described
4977 The B<-style> argument is used to incorporate cascading stylesheets
4978 into your code. See the section on CASCADING STYLESHEETS for more
4981 The B<-lang> argument is used to incorporate a language attribute into
4982 the <html> tag. For example:
4984 print $q->start_html(-lang=>'fr-CA');
4986 The default if not specified is "en-US" for US English, unless the
4987 -dtd parameter specifies an HTML 2.0 or 3.2 DTD, in which case the
4988 lang attribute is left off. You can force the lang attribute to left
4989 off in other cases by passing an empty string (-lang=>'').
4991 The B<-encoding> argument can be used to specify the character set for
4992 XHTML. It defaults to iso-8859-1 if not specified.
4994 The B<-declare_xml> argument, when used in conjunction with XHTML,
4995 will put a <?xml> declaration at the top of the HTML header. The sole
4996 purpose of this declaration is to declare the character set
4997 encoding. In the absence of -declare_xml, the output HTML will contain
4998 a <meta> tag that specifies the encoding, allowing the HTML to pass
4999 most validators. The default for -declare_xml is false.
5001 You can place other arbitrary HTML elements to the <head> section with the
5002 B<-head> tag. For example, to place the rarely-used <link> element in the
5003 head section, use this:
5005 print start_html(-head=>Link({-rel=>'next',
5006 -href=>'http://www.capricorn.com/s2.html'}));
5008 To incorporate multiple HTML elements into the <head> section, just pass an
5011 print start_html(-head=>[
5013 -href=>'http://www.capricorn.com/s2.html'}),
5014 Link({-rel=>'previous',
5015 -href=>'http://www.capricorn.com/s1.html'})
5019 And here's how to create an HTTP-EQUIV <meta> tag:
5021 print start_html(-head=>meta({-http_equiv => 'Content-Type',
5022 -content => 'text/html'}))
5025 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
5026 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
5027 to add Netscape JavaScript calls to your pages. B<-script> should
5028 point to a block of text containing JavaScript function definitions.
5029 This block will be placed within a <script> block inside the HTML (not
5030 HTTP) header. The block is placed in the header in order to give your
5031 page a fighting chance of having all its JavaScript functions in place
5032 even if the user presses the stop button before the page has loaded
5033 completely. CGI.pm attempts to format the script in such a way that
5034 JavaScript-naive browsers will not choke on the code: unfortunately
5035 there are some browsers, such as Chimera for Unix, that get confused
5038 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
5039 code to execute when the page is respectively opened and closed by the
5040 browser. Usually these parameters are calls to functions defined in the
5046 // Ask a silly question
5047 function riddle_me_this() {
5048 var r = prompt("What walks on four legs in the morning, " +
5049 "two legs in the afternoon, " +
5050 "and three legs in the evening?");
5053 // Get a silly answer
5054 function response(answer) {
5055 if (answer == "man")
5056 alert("Right you are!");
5058 alert("Wrong! Guess again.");
5061 print start_html(-title=>'The Riddle of the Sphinx',
5064 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
5065 browsers that do not have JavaScript (or browsers where JavaScript is turned
5068 Netscape 3.0 recognizes several attributes of the <script> tag,
5069 including LANGUAGE and SRC. The latter is particularly interesting,
5070 as it allows you to keep the JavaScript code in a file or CGI script
5071 rather than cluttering up each page with the source. To use these
5072 attributes pass a HASH reference in the B<-script> parameter containing
5073 one or more of -language, -src, or -code:
5075 print $q->start_html(-title=>'The Riddle of the Sphinx',
5076 -script=>{-language=>'JAVASCRIPT',
5077 -src=>'/javascript/sphinx.js'}
5080 print $q->(-title=>'The Riddle of the Sphinx',
5081 -script=>{-language=>'PERLSCRIPT',
5082 -code=>'print "hello world!\n;"'}
5086 A final feature allows you to incorporate multiple <script> sections into the
5087 header. Just pass the list of script sections as an array reference.
5088 this allows you to specify different source files for different dialects
5089 of JavaScript. Example:
5091 print $q->start_html(-title=>'The Riddle of the Sphinx',
5093 { -language => 'JavaScript1.0',
5094 -src => '/javascript/utilities10.js'
5096 { -language => 'JavaScript1.1',
5097 -src => '/javascript/utilities11.js'
5099 { -language => 'JavaScript1.2',
5100 -src => '/javascript/utilities12.js'
5102 { -language => 'JavaScript28.2',
5103 -src => '/javascript/utilities219.js'
5108 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
5112 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
5114 for more information about JavaScript.
5116 The old-style positional parameters are as follows:
5120 =item B<Parameters:>
5128 The author's e-mail address (will create a <link rev="MADE"> tag if present
5132 A 'true' flag if you want to include a <base> tag in the header. This
5133 helps resolve relative addresses to absolute ones when the document is moved,
5134 but makes the document hierarchy non-portable. Use with care!
5138 Any other parameters you want to include in the <body> tag. This is a good
5139 place to put Netscape extensions, such as colors and wallpaper patterns.
5143 =head2 ENDING THE HTML DOCUMENT:
5147 This ends an HTML document by printing the </body></html> tags.
5149 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
5152 print q(<a href="$myself">I'm talking to myself.</a>);
5154 self_url() will return a URL, that, when selected, will reinvoke
5155 this script with all its state information intact. This is most
5156 useful when you want to jump around within the document using
5157 internal anchors but you don't want to disrupt the current contents
5158 of the form(s). Something like this will do the trick.
5161 print "<a href=\"$myself#table1\">See table 1</a>";
5162 print "<a href=\"$myself#table2\">See table 2</a>";
5163 print "<a href=\"$myself#yourself\">See for yourself</a>";
5165 If you want more control over what's returned, using the B<url()>
5168 You can also retrieve the unprocessed query string with query_string():
5170 $the_string = query_string;
5172 =head2 OBTAINING THE SCRIPT'S URL
5175 $full_url = url(-full=>1); #alternative syntax
5176 $relative_url = url(-relative=>1);
5177 $absolute_url = url(-absolute=>1);
5178 $url_with_path = url(-path_info=>1);
5179 $url_with_path_and_query = url(-path_info=>1,-query=>1);
5180 $netloc = url(-base => 1);
5182 B<url()> returns the script's URL in a variety of formats. Called
5183 without any arguments, it returns the full form of the URL, including
5184 host name and port number
5186 http://your.host.com/path/to/script.cgi
5188 You can modify this format with the following named arguments:
5194 If true, produce an absolute URL, e.g.
5200 Produce a relative URL. This is useful if you want to reinvoke your
5201 script with different parameters. For example:
5207 Produce the full URL, exactly as if called without any arguments.
5208 This overrides the -relative and -absolute arguments.
5210 =item B<-path> (B<-path_info>)
5212 Append the additional path information to the URL. This can be
5213 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
5214 is provided as a synonym.
5216 =item B<-query> (B<-query_string>)
5218 Append the query string to the URL. This can be combined with
5219 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
5224 Generate just the protocol and net location, as in http://www.foo.com:8000
5228 If Apache's mod_rewrite is turned on, then the script name and path
5229 info probably won't match the request that the user sent. Set
5230 -rewrite=>1 (default) to return URLs that match what the user sent
5231 (the original request URI). Set -rewrite->0 to return URLs that match
5232 the URL after mod_rewrite's rules have run. Because the additional
5233 path information only makes sense in the context of the rewritten URL,
5234 -rewrite is set to false when you request path info in the URL.
5238 =head2 MIXING POST AND URL PARAMETERS
5240 $color = url_param('color');
5242 It is possible for a script to receive CGI parameters in the URL as
5243 well as in the fill-out form by creating a form that POSTs to a URL
5244 containing a query string (a "?" mark followed by arguments). The
5245 B<param()> method will always return the contents of the POSTed
5246 fill-out form, ignoring the URL's query string. To retrieve URL
5247 parameters, call the B<url_param()> method. Use it in the same way as
5248 B<param()>. The main difference is that it allows you to read the
5249 parameters, but not set them.
5252 Under no circumstances will the contents of the URL query string
5253 interfere with similarly-named CGI parameters in POSTed forms. If you
5254 try to mix a URL query string with a form submitted with the GET
5255 method, the results will not be what you expect.
5257 =head1 CREATING STANDARD HTML ELEMENTS:
5259 CGI.pm defines general HTML shortcut methods for most, if not all of
5260 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
5261 HTML element and return a fragment of HTML text that you can then
5262 print or manipulate as you like. Each shortcut returns a fragment of
5263 HTML code that you can append to a string, save to a file, or, most
5264 commonly, print out so that it displays in the browser window.
5266 This example shows how to use the HTML methods:
5268 print $q->blockquote(
5269 "Many years ago on the island of",
5270 $q->a({href=>"http://crete.org/"},"Crete"),
5271 "there lived a Minotaur named",
5272 $q->strong("Fred."),
5276 This results in the following HTML code (extra newlines have been
5277 added for readability):
5280 Many years ago on the island of
5281 <a href="http://crete.org/">Crete</a> there lived
5282 a minotaur named <strong>Fred.</strong>
5286 If you find the syntax for calling the HTML shortcuts awkward, you can
5287 import them into your namespace and dispense with the object syntax
5288 completely (see the next section for more details):
5290 use CGI ':standard';
5292 "Many years ago on the island of",
5293 a({href=>"http://crete.org/"},"Crete"),
5294 "there lived a minotaur named",
5299 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
5301 The HTML methods will accept zero, one or multiple arguments. If you
5302 provide no arguments, you get a single tag:
5306 If you provide one or more string arguments, they are concatenated
5307 together with spaces and placed between opening and closing tags:
5309 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
5311 If the first argument is an associative array reference, then the keys
5312 and values of the associative array become the HTML tag's attributes:
5314 print a({-href=>'fred.html',-target=>'_new'},
5315 "Open a new frame");
5317 <a href="fred.html",target="_new">Open a new frame</a>
5319 You may dispense with the dashes in front of the attribute names if
5322 print img {src=>'fred.gif',align=>'LEFT'};
5324 <img align="LEFT" src="fred.gif">
5326 Sometimes an HTML tag attribute has no argument. For example, ordered
5327 lists can be marked as COMPACT. The syntax for this is an argument that
5328 that points to an undef string:
5330 print ol({compact=>undef},li('one'),li('two'),li('three'));
5332 Prior to CGI.pm version 2.41, providing an empty ('') string as an
5333 attribute argument was the same as providing undef. However, this has
5334 changed in order to accommodate those who want to create tags of the form
5335 <img alt="">. The difference is shown in these two pieces of code:
5338 img({alt=>undef}) <img alt>
5339 img({alt=>''}) <img alt="">
5341 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
5343 One of the cool features of the HTML shortcuts is that they are
5344 distributive. If you give them an argument consisting of a
5345 B<reference> to a list, the tag will be distributed across each
5346 element of the list. For example, here's one way to make an ordered
5350 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
5353 This example will result in HTML output that looks like this:
5356 <li type="disc">Sneezy</li>
5357 <li type="disc">Doc</li>
5358 <li type="disc">Sleepy</li>
5359 <li type="disc">Happy</li>
5362 This is extremely useful for creating tables. For example:
5364 print table({-border=>undef},
5365 caption('When Should You Eat Your Vegetables?'),
5366 Tr({-align=>CENTER,-valign=>TOP},
5368 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
5369 td(['Tomatoes' , 'no', 'yes', 'yes']),
5370 td(['Broccoli' , 'no', 'no', 'yes']),
5371 td(['Onions' , 'yes','yes', 'yes'])
5376 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
5378 Consider this bit of code:
5380 print blockquote(em('Hi'),'mom!'));
5382 It will ordinarily return the string that you probably expect, namely:
5384 <blockquote><em>Hi</em> mom!</blockquote>
5386 Note the space between the element "Hi" and the element "mom!".
5387 CGI.pm puts the extra space there using array interpolation, which is
5388 controlled by the magic $" variable. Sometimes this extra space is
5389 not what you want, for example, when you are trying to align a series
5390 of images. In this case, you can simply change the value of $" to an
5395 print blockquote(em('Hi'),'mom!'));
5398 I suggest you put the code in a block as shown here. Otherwise the
5399 change to $" will affect all subsequent code until you explicitly
5402 =head2 NON-STANDARD HTML SHORTCUTS
5404 A few HTML tags don't follow the standard pattern for various
5407 B<comment()> generates an HTML comment (<!-- comment -->). Call it
5410 print comment('here is my comment');
5412 Because of conflicts with built-in Perl functions, the following functions
5413 begin with initial caps:
5422 In addition, start_html(), end_html(), start_form(), end_form(),
5423 start_multipart_form() and all the fill-out form tags are special.
5424 See their respective sections.
5426 =head2 AUTOESCAPING HTML
5428 By default, all HTML that is emitted by the form-generating functions
5429 is passed through a function called escapeHTML():
5433 =item $escaped_string = escapeHTML("unescaped string");
5435 Escape HTML formatting characters in a string.
5439 Provided that you have specified a character set of ISO-8859-1 (the
5440 default), the standard HTML escaping rules will be used. The "<"
5441 character becomes "<", ">" becomes ">", "&" becomes "&", and
5442 the quote character becomes """. In addition, the hexadecimal
5443 0x8b and 0x9b characters, which some browsers incorrectly interpret
5444 as the left and right angle-bracket characters, are replaced by their
5445 numeric character entities ("‹" and "›"). If you manually change
5446 the charset, either by calling the charset() method explicitly or by
5447 passing a -charset argument to header(), then B<all> characters will
5448 be replaced by their numeric entities, since CGI.pm has no lookup
5449 table for all the possible encodings.
5451 The automatic escaping does not apply to other shortcuts, such as
5452 h1(). You should call escapeHTML() yourself on untrusted data in
5453 order to protect your pages against nasty tricks that people may enter
5454 into guestbooks, etc.. To change the character set, use charset().
5455 To turn autoescaping off completely, use autoEscape(0):
5459 =item $charset = charset([$charset]);
5461 Get or set the current character set.
5463 =item $flag = autoEscape([$flag]);
5465 Get or set the value of the autoescape flag.
5469 =head2 PRETTY-PRINTING HTML
5471 By default, all the HTML produced by these functions comes out as one
5472 long line without carriage returns or indentation. This is yuck, but
5473 it does reduce the size of the documents by 10-20%. To get
5474 pretty-printed output, please use L<CGI::Pretty>, a subclass
5475 contributed by Brian Paulsen.
5477 =head1 CREATING FILL-OUT FORMS:
5479 I<General note> The various form-creating methods all return strings
5480 to the caller, containing the tag or tags that will create the requested
5481 form element. You are responsible for actually printing out these strings.
5482 It's set up this way so that you can place formatting tags
5483 around the form elements.
5485 I<Another note> The default values that you specify for the forms are only
5486 used the B<first> time the script is invoked (when there is no query
5487 string). On subsequent invocations of the script (when there is a query
5488 string), the former values are used even if they are blank.
5490 If you want to change the value of a field from its previous value, you have two
5493 (1) call the param() method to set it.
5495 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
5496 This forces the default value to be used, regardless of the previous value:
5498 print textfield(-name=>'field_name',
5499 -default=>'starting value',
5504 I<Yet another note> By default, the text and labels of form elements are
5505 escaped according to HTML rules. This means that you can safely use
5506 "<CLICK ME>" as the label for a button. However, it also interferes with
5507 your ability to incorporate special HTML character sequences, such as Á,
5508 into your fields. If you wish to turn off automatic escaping, call the
5509 autoEscape() method with a false value immediately after creating the CGI object:
5514 I<A Lurking Trap!> Some of the form-element generating methods return
5515 multiple tags. In a scalar context, the tags will be concatenated
5516 together with spaces, or whatever is the current value of the $"
5517 global. In a list context, the methods will return a list of
5518 elements, allowing you to modify them if you wish. Usually you will
5519 not notice this behavior, but beware of this:
5521 printf("%s\n",end_form())
5523 end_form() produces several tags, and only the first of them will be
5524 printed because the format only expects one value.
5529 =head2 CREATING AN ISINDEX TAG
5531 print isindex(-action=>$action);
5535 print isindex($action);
5537 Prints out an <isindex> tag. Not very exciting. The parameter
5538 -action specifies the URL of the script to process the query. The
5539 default is to process the query with the current script.
5541 =head2 STARTING AND ENDING A FORM
5543 print start_form(-method=>$method,
5545 -enctype=>$encoding);
5546 <... various form stuff ...>
5551 print start_form($method,$action,$encoding);
5552 <... various form stuff ...>
5555 start_form() will return a <form> tag with the optional method,
5556 action and form encoding that you specify. The defaults are:
5560 enctype: application/x-www-form-urlencoded
5562 endform() returns the closing </form> tag.
5564 Start_form()'s enctype argument tells the browser how to package the various
5565 fields of the form before sending the form to the server. Two
5566 values are possible:
5568 B<Note:> This method was previously named startform(), and startform()
5569 is still recognized as an alias.
5573 =item B<application/x-www-form-urlencoded>
5575 This is the older type of encoding used by all browsers prior to
5576 Netscape 2.0. It is compatible with many CGI scripts and is
5577 suitable for short fields containing text data. For your
5578 convenience, CGI.pm stores the name of this encoding
5579 type in B<&CGI::URL_ENCODED>.
5581 =item B<multipart/form-data>
5583 This is the newer type of encoding introduced by Netscape 2.0.
5584 It is suitable for forms that contain very large fields or that
5585 are intended for transferring binary data. Most importantly,
5586 it enables the "file upload" feature of Netscape 2.0 forms. For
5587 your convenience, CGI.pm stores the name of this encoding type
5588 in B<&CGI::MULTIPART>
5590 Forms that use this type of encoding are not easily interpreted
5591 by CGI scripts unless they use CGI.pm or another library designed
5594 If XHTML is activated (the default), then forms will be automatically
5595 created using this type of encoding.
5599 For compatibility, the start_form() method uses the older form of
5600 encoding by default. If you want to use the newer form of encoding
5601 by default, you can call B<start_multipart_form()> instead of
5604 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
5605 for use with JavaScript. The -name parameter gives the
5606 form a name so that it can be identified and manipulated by
5607 JavaScript functions. -onSubmit should point to a JavaScript
5608 function that will be executed just before the form is submitted to your
5609 server. You can use this opportunity to check the contents of the form
5610 for consistency and completeness. If you find something wrong, you
5611 can put up an alert box or maybe fix things up yourself. You can
5612 abort the submission by returning false from this function.
5614 Usually the bulk of JavaScript functions are defined in a <script>
5615 block in the HTML header and -onSubmit points to one of these function
5616 call. See start_html() for details.
5618 =head2 FORM ELEMENTS
5620 After starting a form, you will typically create one or more
5621 textfields, popup menus, radio groups and other form elements. Each
5622 of these elements takes a standard set of named arguments. Some
5623 elements also have optional arguments. The standard arguments are as
5630 The name of the field. After submission this name can be used to
5631 retrieve the field's value using the param() method.
5633 =item B<-value>, B<-values>
5635 The initial value of the field which will be returned to the script
5636 after form submission. Some form elements, such as text fields, take
5637 a single scalar -value argument. Others, such as popup menus, take a
5638 reference to an array of values. The two arguments are synonyms.
5642 A numeric value that sets the order in which the form element receives
5643 focus when the user presses the tab key. Elements with lower values
5644 receive focus first.
5648 A string identifier that can be used to identify this element to
5649 JavaScript and DHTML.
5653 A boolean, which, if true, forces the element to take on the value
5654 specified by B<-value>, overriding the sticky behavior described
5655 earlier for the B<-no_sticky> pragma.
5657 =item B<-onChange>, B<-onFocus>, B<-onBlur>, B<-onMouseOver>, B<-onMouseOut>, B<-onSelect>
5659 These are used to assign JavaScript event handlers. See the
5660 JavaScripting section for more details.
5664 Other common arguments are described in the next section. In addition
5665 to these, all attributes described in the HTML specifications are
5668 =head2 CREATING A TEXT FIELD
5670 print textfield(-name=>'field_name',
5671 -value=>'starting value',
5676 print textfield('field_name','starting value',50,80);
5678 textfield() will return a text input field.
5686 The first parameter is the required name for the field (-name).
5690 The optional second parameter is the default starting value for the field
5691 contents (-value, formerly known as -default).
5695 The optional third parameter is the size of the field in
5700 The optional fourth parameter is the maximum number of characters the
5701 field will accept (-maxlength).
5705 As with all these methods, the field will be initialized with its
5706 previous contents from earlier invocations of the script.
5707 When the form is processed, the value of the text field can be
5710 $value = param('foo');
5712 If you want to reset it from its initial value after the script has been
5713 called once, you can do so like this:
5715 param('foo',"I'm taking over this value!");
5717 =head2 CREATING A BIG TEXT FIELD
5719 print textarea(-name=>'foo',
5720 -default=>'starting value',
5726 print textarea('foo','starting value',10,50);
5728 textarea() is just like textfield, but it allows you to specify
5729 rows and columns for a multiline text entry box. You can provide
5730 a starting value for the field, which can be long and contain
5733 =head2 CREATING A PASSWORD FIELD
5735 print password_field(-name=>'secret',
5736 -value=>'starting value',
5741 print password_field('secret','starting value',50,80);
5743 password_field() is identical to textfield(), except that its contents
5744 will be starred out on the web page.
5746 =head2 CREATING A FILE UPLOAD FIELD
5748 print filefield(-name=>'uploaded_file',
5749 -default=>'starting value',
5754 print filefield('uploaded_file','starting value',50,80);
5756 filefield() will return a file upload field for Netscape 2.0 browsers.
5757 In order to take full advantage of this I<you must use the new
5758 multipart encoding scheme> for the form. You can do this either
5759 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5760 or by calling the new method B<start_multipart_form()> instead of
5761 vanilla B<start_form()>.
5769 The first parameter is the required name for the field (-name).
5773 The optional second parameter is the starting value for the field contents
5774 to be used as the default file name (-default).
5776 For security reasons, browsers don't pay any attention to this field,
5777 and so the starting value will always be blank. Worse, the field
5778 loses its "sticky" behavior and forgets its previous contents. The
5779 starting value field is called for in the HTML specification, however,
5780 and possibly some browser will eventually provide support for it.
5784 The optional third parameter is the size of the field in
5789 The optional fourth parameter is the maximum number of characters the
5790 field will accept (-maxlength).
5794 When the form is processed, you can retrieve the entered filename
5797 $filename = param('uploaded_file');
5799 Different browsers will return slightly different things for the
5800 name. Some browsers return the filename only. Others return the full
5801 path to the file, using the path conventions of the user's machine.
5802 Regardless, the name returned is always the name of the file on the
5803 I<user's> machine, and is unrelated to the name of the temporary file
5804 that CGI.pm creates during upload spooling (see below).
5806 The filename returned is also a file handle. You can read the contents
5807 of the file using standard Perl file reading calls:
5809 # Read a text file and print it out
5810 while (<$filename>) {
5814 # Copy a binary file to somewhere safe
5815 open (OUTFILE,">>/usr/local/web/users/feedback");
5816 while ($bytesread=read($filename,$buffer,1024)) {
5817 print OUTFILE $buffer;
5820 However, there are problems with the dual nature of the upload fields.
5821 If you C<use strict>, then Perl will complain when you try to use a
5822 string as a filehandle. You can get around this by placing the file
5823 reading code in a block containing the C<no strict> pragma. More
5824 seriously, it is possible for the remote user to type garbage into the
5825 upload field, in which case what you get from param() is not a
5826 filehandle at all, but a string.
5828 To be safe, use the I<upload()> function (new in version 2.47). When
5829 called with the name of an upload field, I<upload()> returns a
5830 filehandle, or undef if the parameter is not a valid filehandle.
5832 $fh = upload('uploaded_file');
5837 In an list context, upload() will return an array of filehandles.
5838 This makes it possible to create forms that use the same name for
5839 multiple upload fields.
5841 This is the recommended idiom.
5843 When a file is uploaded the browser usually sends along some
5844 information along with it in the format of headers. The information
5845 usually includes the MIME content type. Future browsers may send
5846 other information as well (such as modification date and size). To
5847 retrieve this information, call uploadInfo(). It returns a reference to
5848 an associative array containing all the document headers.
5850 $filename = param('uploaded_file');
5851 $type = uploadInfo($filename)->{'Content-Type'};
5852 unless ($type eq 'text/html') {
5853 die "HTML FILES ONLY!";
5856 If you are using a machine that recognizes "text" and "binary" data
5857 modes, be sure to understand when and how to use them (see the Camel book).
5858 Otherwise you may find that binary files are corrupted during file
5861 There are occasionally problems involving parsing the uploaded file.
5862 This usually happens when the user presses "Stop" before the upload is
5863 finished. In this case, CGI.pm will return undef for the name of the
5864 uploaded file and set I<cgi_error()> to the string "400 Bad request
5865 (malformed multipart POST)". This error message is designed so that
5866 you can incorporate it into a status code to be sent to the browser.
5869 $file = upload('uploaded_file');
5870 if (!$file && cgi_error) {
5871 print header(-status=>cgi_error);
5875 You are free to create a custom HTML page to complain about the error,
5878 You can set up a callback that will be called whenever a file upload
5879 is being read during the form processing. This is much like the
5880 UPLOAD_HOOK facility available in Apache::Request, with the exception
5881 that the first argument to the callback is an Apache::Upload object,
5882 here it's the remote filename.
5884 $q = CGI->new(\&hook,$data);
5888 my ($filename, $buffer, $bytes_read, $data) = @_;
5889 print "Read $bytes_read bytes of $filename\n";
5892 If using the function-oriented interface, call the CGI::upload_hook()
5893 method before calling param() or any other CGI functions:
5895 CGI::upload_hook(\&hook,$data);
5897 This method is not exported by default. You will have to import it
5898 explicitly if you wish to use it without the CGI:: prefix.
5900 If you are using CGI.pm on a Windows platform and find that binary
5901 files get slightly larger when uploaded but that text files remain the
5902 same, then you have forgotten to activate binary mode on the output
5903 filehandle. Be sure to call binmode() on any handle that you create
5904 to write the uploaded file to disk.
5906 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5907 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5908 recognized. See textfield() for details.
5910 =head2 CREATING A POPUP MENU
5912 print popup_menu('menu_name',
5913 ['eenie','meenie','minie'],
5918 %labels = ('eenie'=>'your first choice',
5919 'meenie'=>'your second choice',
5920 'minie'=>'your third choice');
5921 %attributes = ('eenie'=>{'class'=>'class of first choice'});
5922 print popup_menu('menu_name',
5923 ['eenie','meenie','minie'],
5924 'meenie',\%labels,\%attributes);
5926 -or (named parameter style)-
5928 print popup_menu(-name=>'menu_name',
5929 -values=>['eenie','meenie','minie'],
5932 -attributes=>\%attributes);
5934 popup_menu() creates a menu.
5940 The required first argument is the menu's name (-name).
5944 The required second argument (-values) is an array B<reference>
5945 containing the list of menu items in the menu. You can pass the
5946 method an anonymous array, as shown in the example, or a reference to
5947 a named array, such as "\@foo".
5951 The optional third parameter (-default) is the name of the default
5952 menu choice. If not specified, the first item will be the default.
5953 The values of the previous choice will be maintained across queries.
5957 The optional fourth parameter (-labels) is provided for people who
5958 want to use different values for the user-visible label inside the
5959 popup menu and the value returned to your script. It's a pointer to an
5960 associative array relating menu values to user-visible labels. If you
5961 leave this parameter blank, the menu values will be displayed by
5962 default. (You can also leave a label undefined if you want to).
5966 The optional fifth parameter (-attributes) is provided to assign
5967 any of the common HTML attributes to an individual menu item. It's
5968 a pointer to an associative array relating menu values to another
5969 associative array with the attribute's name as the key and the
5970 attribute's value as the value.
5974 When the form is processed, the selected value of the popup menu can
5977 $popup_menu_value = param('menu_name');
5979 =head2 CREATING AN OPTION GROUP
5981 Named parameter style
5983 print popup_menu(-name=>'menu_name',
5984 -values=>[qw/eenie meenie minie/,
5985 optgroup(-name=>'optgroup_name',
5986 -values => ['moe','catch'],
5987 -attributes=>{'catch'=>{'class'=>'red'}})],
5988 -labels=>{'eenie'=>'one',
5991 -default=>'meenie');
5994 print popup_menu('menu_name',
5995 ['eenie','meenie','minie',
5996 optgroup('optgroup_name', ['moe', 'catch'],
5997 {'catch'=>{'class'=>'red'}})],'meenie',
5998 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
6000 optgroup() creates an option group within a popup menu.
6006 The required first argument (B<-name>) is the label attribute of the
6007 optgroup and is B<not> inserted in the parameter list of the query.
6011 The required second argument (B<-values>) is an array reference
6012 containing the list of menu items in the menu. You can pass the
6013 method an anonymous array, as shown in the example, or a reference
6014 to a named array, such as \@foo. If you pass a HASH reference,
6015 the keys will be used for the menu values, and the values will be
6016 used for the menu labels (see -labels below).
6020 The optional third parameter (B<-labels>) allows you to pass a reference
6021 to an associative array containing user-visible labels for one or more
6022 of the menu items. You can use this when you want the user to see one
6023 menu string, but have the browser return your program a different one.
6024 If you don't specify this, the value string will be used instead
6025 ("eenie", "meenie" and "minie" in this example). This is equivalent
6026 to using a hash reference for the -values parameter.
6030 An optional fourth parameter (B<-labeled>) can be set to a true value
6031 and indicates that the values should be used as the label attribute
6032 for each option element within the optgroup.
6036 An optional fifth parameter (-novals) can be set to a true value and
6037 indicates to suppress the val attribute in each option element within
6040 See the discussion on optgroup at W3C
6041 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
6046 An optional sixth parameter (-attributes) is provided to assign
6047 any of the common HTML attributes to an individual menu item. It's
6048 a pointer to an associative array relating menu values to another
6049 associative array with the attribute's name as the key and the
6050 attribute's value as the value.
6054 =head2 CREATING A SCROLLING LIST
6056 print scrolling_list('list_name',
6057 ['eenie','meenie','minie','moe'],
6058 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
6061 print scrolling_list('list_name',
6062 ['eenie','meenie','minie','moe'],
6063 ['eenie','moe'],5,'true',
6064 \%labels,%attributes);
6068 print scrolling_list(-name=>'list_name',
6069 -values=>['eenie','meenie','minie','moe'],
6070 -default=>['eenie','moe'],
6074 -attributes=>\%attributes);
6076 scrolling_list() creates a scrolling list.
6080 =item B<Parameters:>
6084 The first and second arguments are the list name (-name) and values
6085 (-values). As in the popup menu, the second argument should be an
6090 The optional third argument (-default) can be either a reference to a
6091 list containing the values to be selected by default, or can be a
6092 single value to select. If this argument is missing or undefined,
6093 then nothing is selected when the list first appears. In the named
6094 parameter version, you can use the synonym "-defaults" for this
6099 The optional fourth argument is the size of the list (-size).
6103 The optional fifth argument can be set to true to allow multiple
6104 simultaneous selections (-multiple). Otherwise only one selection
6105 will be allowed at a time.
6109 The optional sixth argument is a pointer to an associative array
6110 containing long user-visible labels for the list items (-labels).
6111 If not provided, the values will be displayed.
6115 The optional sixth parameter (-attributes) is provided to assign
6116 any of the common HTML attributes to an individual menu item. It's
6117 a pointer to an associative array relating menu values to another
6118 associative array with the attribute's name as the key and the
6119 attribute's value as the value.
6121 When this form is processed, all selected list items will be returned as
6122 a list under the parameter name 'list_name'. The values of the
6123 selected items can be retrieved with:
6125 @selected = param('list_name');
6129 =head2 CREATING A GROUP OF RELATED CHECKBOXES
6131 print checkbox_group(-name=>'group_name',
6132 -values=>['eenie','meenie','minie','moe'],
6133 -default=>['eenie','moe'],
6136 -attributes=>\%attributes);
6138 print checkbox_group('group_name',
6139 ['eenie','meenie','minie','moe'],
6140 ['eenie','moe'],'true',\%labels,
6141 {'moe'=>{'class'=>'red'}});
6143 HTML3-COMPATIBLE BROWSERS ONLY:
6145 print checkbox_group(-name=>'group_name',
6146 -values=>['eenie','meenie','minie','moe'],
6147 -rows=2,-columns=>2);
6150 checkbox_group() creates a list of checkboxes that are related
6155 =item B<Parameters:>
6159 The first and second arguments are the checkbox name and values,
6160 respectively (-name and -values). As in the popup menu, the second
6161 argument should be an array reference. These values are used for the
6162 user-readable labels printed next to the checkboxes as well as for the
6163 values passed to your script in the query string.
6167 The optional third argument (-default) can be either a reference to a
6168 list containing the values to be checked by default, or can be a
6169 single value to checked. If this argument is missing or undefined,
6170 then nothing is selected when the list first appears.
6174 The optional fourth argument (-linebreak) can be set to true to place
6175 line breaks between the checkboxes so that they appear as a vertical
6176 list. Otherwise, they will be strung together on a horizontal line.
6181 The optional b<-labels> argument is a pointer to an associative array
6182 relating the checkbox values to the user-visible labels that will be
6183 printed next to them. If not provided, the values will be used as the
6187 Modern browsers can take advantage of the optional parameters
6188 B<-rows>, and B<-columns>. These parameters cause checkbox_group() to
6189 return an HTML3 compatible table containing the checkbox group
6190 formatted with the specified number of rows and columns. You can
6191 provide just the -columns parameter if you wish; checkbox_group will
6192 calculate the correct number of rows for you.
6195 The optional B<-attributes> argument is provided to assign any of the
6196 common HTML attributes to an individual menu item. It's a pointer to
6197 an associative array relating menu values to another associative array
6198 with the attribute's name as the key and the attribute's value as the
6201 The optional B<-tabindex> argument can be used to control the order in which
6202 radio buttons receive focus when the user presses the tab button. If
6203 passed a scalar numeric value, the first element in the group will
6204 receive this tab index and subsequent elements will be incremented by
6205 one. If given a reference to an array of radio button values, then
6206 the indexes will be jiggered so that the order specified in the array
6207 will correspond to the tab order. You can also pass a reference to a
6208 hash in which the hash keys are the radio button values and the values
6209 are the tab indexes of each button. Examples:
6211 -tabindex => 100 # this group starts at index 100 and counts up
6212 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
6213 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
6215 When the form is processed, all checked boxes will be returned as
6216 a list under the parameter name 'group_name'. The values of the
6217 "on" checkboxes can be retrieved with:
6219 @turned_on = param('group_name');
6221 The value returned by checkbox_group() is actually an array of button
6222 elements. You can capture them and use them within tables, lists,
6223 or in other creative ways:
6225 @h = checkbox_group(-name=>'group_name',-values=>\@values);
6226 &use_in_creative_way(@h);
6228 =head2 CREATING A STANDALONE CHECKBOX
6230 print checkbox(-name=>'checkbox_name',
6233 -label=>'CLICK ME');
6237 print checkbox('checkbox_name','checked','ON','CLICK ME');
6239 checkbox() is used to create an isolated checkbox that isn't logically
6240 related to any others.
6244 =item B<Parameters:>
6248 The first parameter is the required name for the checkbox (-name). It
6249 will also be used for the user-readable label printed next to the
6254 The optional second parameter (-checked) specifies that the checkbox
6255 is turned on by default. Synonyms are -selected and -on.
6259 The optional third parameter (-value) specifies the value of the
6260 checkbox when it is checked. If not provided, the word "on" is
6265 The optional fourth parameter (-label) is the user-readable label to
6266 be attached to the checkbox. If not provided, the checkbox name is
6271 The value of the checkbox can be retrieved using:
6273 $turned_on = param('checkbox_name');
6275 =head2 CREATING A RADIO BUTTON GROUP
6277 print radio_group(-name=>'group_name',
6278 -values=>['eenie','meenie','minie'],
6282 -attributes=>\%attributes);
6286 print radio_group('group_name',['eenie','meenie','minie'],
6287 'meenie','true',\%labels,\%attributes);
6290 HTML3-COMPATIBLE BROWSERS ONLY:
6292 print radio_group(-name=>'group_name',
6293 -values=>['eenie','meenie','minie','moe'],
6294 -rows=2,-columns=>2);
6296 radio_group() creates a set of logically-related radio buttons
6297 (turning one member of the group on turns the others off)
6301 =item B<Parameters:>
6305 The first argument is the name of the group and is required (-name).
6309 The second argument (-values) is the list of values for the radio
6310 buttons. The values and the labels that appear on the page are
6311 identical. Pass an array I<reference> in the second argument, either
6312 using an anonymous array, as shown, or by referencing a named array as
6317 The optional third parameter (-default) is the name of the default
6318 button to turn on. If not specified, the first item will be the
6319 default. You can provide a nonexistent button name, such as "-" to
6320 start up with no buttons selected.
6324 The optional fourth parameter (-linebreak) can be set to 'true' to put
6325 line breaks between the buttons, creating a vertical list.
6329 The optional fifth parameter (-labels) is a pointer to an associative
6330 array relating the radio button values to user-visible labels to be
6331 used in the display. If not provided, the values themselves are
6337 All modern browsers can take advantage of the optional parameters
6338 B<-rows>, and B<-columns>. These parameters cause radio_group() to
6339 return an HTML3 compatible table containing the radio group formatted
6340 with the specified number of rows and columns. You can provide just
6341 the -columns parameter if you wish; radio_group will calculate the
6342 correct number of rows for you.
6344 To include row and column headings in the returned table, you
6345 can use the B<-rowheader> and B<-colheader> parameters. Both
6346 of these accept a pointer to an array of headings to use.
6347 The headings are just decorative. They don't reorganize the
6348 interpretation of the radio buttons -- they're still a single named
6351 The optional B<-tabindex> argument can be used to control the order in which
6352 radio buttons receive focus when the user presses the tab button. If
6353 passed a scalar numeric value, the first element in the group will
6354 receive this tab index and subsequent elements will be incremented by
6355 one. If given a reference to an array of radio button values, then
6356 the indexes will be jiggered so that the order specified in the array
6357 will correspond to the tab order. You can also pass a reference to a
6358 hash in which the hash keys are the radio button values and the values
6359 are the tab indexes of each button. Examples:
6361 -tabindex => 100 # this group starts at index 100 and counts up
6362 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
6363 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
6366 The optional B<-attributes> argument is provided to assign any of the
6367 common HTML attributes to an individual menu item. It's a pointer to
6368 an associative array relating menu values to another associative array
6369 with the attribute's name as the key and the attribute's value as the
6372 When the form is processed, the selected radio button can
6375 $which_radio_button = param('group_name');
6377 The value returned by radio_group() is actually an array of button
6378 elements. You can capture them and use them within tables, lists,
6379 or in other creative ways:
6381 @h = radio_group(-name=>'group_name',-values=>\@values);
6382 &use_in_creative_way(@h);
6384 =head2 CREATING A SUBMIT BUTTON
6386 print submit(-name=>'button_name',
6391 print submit('button_name','value');
6393 submit() will create the query submission button. Every form
6394 should have one of these.
6398 =item B<Parameters:>
6402 The first argument (-name) is optional. You can give the button a
6403 name if you have several submission buttons in your form and you want
6404 to distinguish between them.
6408 The second argument (-value) is also optional. This gives the button
6409 a value that will be passed to your script in the query string. The
6410 name will also be used as the user-visible label.
6414 You can use -label as an alias for -value. I always get confused
6415 about which of -name and -value changes the user-visible label on the
6420 You can figure out which button was pressed by using different
6421 values for each one:
6423 $which_one = param('button_name');
6425 =head2 CREATING A RESET BUTTON
6429 reset() creates the "reset" button. Note that it restores the
6430 form to its value from the last time the script was called,
6431 NOT necessarily to the defaults.
6433 Note that this conflicts with the Perl reset() built-in. Use
6434 CORE::reset() to get the original reset function.
6436 =head2 CREATING A DEFAULT BUTTON
6438 print defaults('button_label')
6440 defaults() creates a button that, when invoked, will cause the
6441 form to be completely reset to its defaults, wiping out all the
6442 changes the user ever made.
6444 =head2 CREATING A HIDDEN FIELD
6446 print hidden(-name=>'hidden_name',
6447 -default=>['value1','value2'...]);
6451 print hidden('hidden_name','value1','value2'...);
6453 hidden() produces a text field that can't be seen by the user. It
6454 is useful for passing state variable information from one invocation
6455 of the script to the next.
6459 =item B<Parameters:>
6463 The first argument is required and specifies the name of this
6468 The second argument is also required and specifies its value
6469 (-default). In the named parameter style of calling, you can provide
6470 a single value here or a reference to a whole list
6474 Fetch the value of a hidden field this way:
6476 $hidden_value = param('hidden_name');
6478 Note, that just like all the other form elements, the value of a
6479 hidden field is "sticky". If you want to replace a hidden field with
6480 some other values after the script has been called once you'll have to
6483 param('hidden_name','new','values','here');
6485 =head2 CREATING A CLICKABLE IMAGE BUTTON
6487 print image_button(-name=>'button_name',
6488 -src=>'/source/URL',
6493 print image_button('button_name','/source/URL','MIDDLE');
6495 image_button() produces a clickable image. When it's clicked on the
6496 position of the click is returned to your script as "button_name.x"
6497 and "button_name.y", where "button_name" is the name you've assigned
6502 =item B<Parameters:>
6506 The first argument (-name) is required and specifies the name of this
6511 The second argument (-src) is also required and specifies the URL
6514 The third option (-align, optional) is an alignment type, and may be
6515 TOP, BOTTOM or MIDDLE
6519 Fetch the value of the button this way:
6520 $x = param('button_name.x');
6521 $y = param('button_name.y');
6523 =head2 CREATING A JAVASCRIPT ACTION BUTTON
6525 print button(-name=>'button_name',
6526 -value=>'user visible label',
6527 -onClick=>"do_something()");
6531 print button('button_name',"do_something()");
6533 button() produces a button that is compatible with Netscape 2.0's
6534 JavaScript. When it's pressed the fragment of JavaScript code
6535 pointed to by the B<-onClick> parameter will be executed. On
6536 non-Netscape browsers this form element will probably not even
6541 Netscape browsers versions 1.1 and higher, and all versions of
6542 Internet Explorer, support a so-called "cookie" designed to help
6543 maintain state within a browser session. CGI.pm has several methods
6544 that support cookies.
6546 A cookie is a name=value pair much like the named parameters in a CGI
6547 query string. CGI scripts create one or more cookies and send
6548 them to the browser in the HTTP header. The browser maintains a list
6549 of cookies that belong to a particular Web server, and returns them
6550 to the CGI script during subsequent interactions.
6552 In addition to the required name=value pair, each cookie has several
6553 optional attributes:
6557 =item 1. an expiration time
6559 This is a time/date string (in a special GMT format) that indicates
6560 when a cookie expires. The cookie will be saved and returned to your
6561 script until this expiration date is reached if the user exits
6562 the browser and restarts it. If an expiration date isn't specified, the cookie
6563 will remain active until the user quits the browser.
6567 This is a partial or complete domain name for which the cookie is
6568 valid. The browser will return the cookie to any host that matches
6569 the partial domain name. For example, if you specify a domain name
6570 of ".capricorn.com", then the browser will return the cookie to
6571 Web servers running on any of the machines "www.capricorn.com",
6572 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
6573 must contain at least two periods to prevent attempts to match
6574 on top level domains like ".edu". If no domain is specified, then
6575 the browser will only return the cookie to servers on the host the
6576 cookie originated from.
6580 If you provide a cookie path attribute, the browser will check it
6581 against your script's URL before returning the cookie. For example,
6582 if you specify the path "/cgi-bin", then the cookie will be returned
6583 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
6584 and "/cgi-bin/customer_service/complain.pl", but not to the script
6585 "/cgi-private/site_admin.pl". By default, path is set to "/", which
6586 causes the cookie to be sent to any CGI script on your site.
6588 =item 4. a "secure" flag
6590 If the "secure" attribute is set, the cookie will only be sent to your
6591 script if the CGI request is occurring on a secure channel, such as SSL.
6595 The interface to HTTP cookies is the B<cookie()> method:
6597 $cookie = cookie(-name=>'sessionID',
6600 -path=>'/cgi-bin/database',
6601 -domain=>'.capricorn.org',
6603 print header(-cookie=>$cookie);
6605 B<cookie()> creates a new cookie. Its parameters include:
6611 The name of the cookie (required). This can be any string at all.
6612 Although browsers limit their cookie names to non-whitespace
6613 alphanumeric characters, CGI.pm removes this restriction by escaping
6614 and unescaping cookies behind the scenes.
6618 The value of the cookie. This can be any scalar value,
6619 array reference, or even associative array reference. For example,
6620 you can store an entire associative array into a cookie this way:
6622 $cookie=cookie(-name=>'family information',
6623 -value=>\%childrens_ages);
6627 The optional partial path for which this cookie will be valid, as described
6632 The optional partial domain for which this cookie will be valid, as described
6637 The optional expiration date for this cookie. The format is as described
6638 in the section on the B<header()> method:
6640 "+1h" one hour from now
6644 If set to true, this cookie will only be used within a secure
6649 The cookie created by cookie() must be incorporated into the HTTP
6650 header within the string returned by the header() method:
6652 print header(-cookie=>$my_cookie);
6654 To create multiple cookies, give header() an array reference:
6656 $cookie1 = cookie(-name=>'riddle_name',
6657 -value=>"The Sphynx's Question");
6658 $cookie2 = cookie(-name=>'answers',
6660 print header(-cookie=>[$cookie1,$cookie2]);
6662 To retrieve a cookie, request it by name by calling cookie() method
6663 without the B<-value> parameter:
6667 $riddle = cookie('riddle_name');
6668 %answers = cookie('answers');
6670 Cookies created with a single scalar value, such as the "riddle_name"
6671 cookie, will be returned in that form. Cookies with array and hash
6672 values can also be retrieved.
6674 The cookie and CGI namespaces are separate. If you have a parameter
6675 named 'answers' and a cookie named 'answers', the values retrieved by
6676 param() and cookie() are independent of each other. However, it's
6677 simple to turn a CGI parameter into a cookie, and vice-versa:
6679 # turn a CGI parameter into a cookie
6680 $c=cookie(-name=>'answers',-value=>[param('answers')]);
6682 param(-name=>'answers',-value=>[cookie('answers')]);
6684 If you call cookie() without any parameters, it will return a list of
6685 the names of all cookies passed to your script:
6687 @cookies = cookie();
6689 See the B<cookie.cgi> example script for some ideas on how to use
6690 cookies effectively.
6692 =head1 WORKING WITH FRAMES
6694 It's possible for CGI.pm scripts to write into several browser panels
6695 and windows using the HTML 4 frame mechanism. There are three
6696 techniques for defining new frames programmatically:
6700 =item 1. Create a <Frameset> document
6702 After writing out the HTTP header, instead of creating a standard
6703 HTML document using the start_html() call, create a <frameset>
6704 document that defines the frames on the page. Specify your script(s)
6705 (with appropriate parameters) as the SRC for each of the frames.
6707 There is no specific support for creating <frameset> sections
6708 in CGI.pm, but the HTML is very simple to write. See the frame
6709 documentation in Netscape's home pages for details
6711 http://home.netscape.com/assist/net_sites/frames.html
6713 =item 2. Specify the destination for the document in the HTTP header
6715 You may provide a B<-target> parameter to the header() method:
6717 print header(-target=>'ResultsWindow');
6719 This will tell the browser to load the output of your script into the
6720 frame named "ResultsWindow". If a frame of that name doesn't already
6721 exist, the browser will pop up a new window and load your script's
6722 document into that. There are a number of magic names that you can
6723 use for targets. See the frame documents on Netscape's home pages for
6726 =item 3. Specify the destination for the document in the <form> tag
6728 You can specify the frame to load in the FORM tag itself. With
6729 CGI.pm it looks like this:
6731 print start_form(-target=>'ResultsWindow');
6733 When your script is reinvoked by the form, its output will be loaded
6734 into the frame named "ResultsWindow". If one doesn't already exist
6735 a new window will be created.
6739 The script "frameset.cgi" in the examples directory shows one way to
6740 create pages in which the fill-out form and the response live in
6741 side-by-side frames.
6743 =head1 SUPPORT FOR JAVASCRIPT
6745 Netscape versions 2.0 and higher incorporate an interpreted language
6746 called JavaScript. Internet Explorer, 3.0 and higher, supports a
6747 closely-related dialect called JScript. JavaScript isn't the same as
6748 Java, and certainly isn't at all the same as Perl, which is a great
6749 pity. JavaScript allows you to programmatically change the contents of
6750 fill-out forms, create new windows, and pop up dialog box from within
6751 Netscape itself. From the point of view of CGI scripting, JavaScript
6752 is quite useful for validating fill-out forms prior to submitting
6755 You'll need to know JavaScript in order to use it. There are many good
6756 sources in bookstores and on the web.
6758 The usual way to use JavaScript is to define a set of functions in a
6759 <SCRIPT> block inside the HTML header and then to register event
6760 handlers in the various elements of the page. Events include such
6761 things as the mouse passing over a form element, a button being
6762 clicked, the contents of a text field changing, or a form being
6763 submitted. When an event occurs that involves an element that has
6764 registered an event handler, its associated JavaScript code gets
6767 The elements that can register event handlers include the <BODY> of an
6768 HTML document, hypertext links, all the various elements of a fill-out
6769 form, and the form itself. There are a large number of events, and
6770 each applies only to the elements for which it is relevant. Here is a
6777 The browser is loading the current document. Valid in:
6779 + The HTML <BODY> section only.
6783 The browser is closing the current page or frame. Valid for:
6785 + The HTML <BODY> section only.
6789 The user has pressed the submit button of a form. This event happens
6790 just before the form is submitted, and your function can return a
6791 value of false in order to abort the submission. Valid for:
6797 The mouse has clicked on an item in a fill-out form. Valid for:
6799 + Buttons (including submit, reset, and image buttons)
6805 The user has changed the contents of a field. Valid for:
6816 The user has selected a field to work with. Valid for:
6827 The user has deselected a field (gone to work somewhere else). Valid
6839 The user has changed the part of a text field that is selected. Valid
6847 =item B<onMouseOver>
6849 The mouse has moved over an element.
6860 The mouse has moved off an element.
6871 In order to register a JavaScript event handler with an HTML element,
6872 just use the event name as a parameter when you call the corresponding
6873 CGI method. For example, to have your validateAge() JavaScript code
6874 executed every time the textfield named "age" changes, generate the
6877 print textfield(-name=>'age',-onChange=>"validateAge(this)");
6879 This example assumes that you've already declared the validateAge()
6880 function by incorporating it into a <SCRIPT> block. The CGI.pm
6881 start_html() method provides a convenient way to create this section.
6883 Similarly, you can create a form that checks itself over for
6884 consistency and alerts the user if some essential value is missing by
6885 creating it this way:
6886 print startform(-onSubmit=>"validateMe(this)");
6888 See the javascript.cgi script for a demonstration of how this all
6892 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
6894 CGI.pm has limited support for HTML3's cascading style sheets (css).
6895 To incorporate a stylesheet into your document, pass the
6896 start_html() method a B<-style> parameter. The value of this
6897 parameter may be a scalar, in which case it is treated as the source
6898 URL for the stylesheet, or it may be a hash reference. In the latter
6899 case you should provide the hash with one or more of B<-src> or
6900 B<-code>. B<-src> points to a URL where an externally-defined
6901 stylesheet can be found. B<-code> points to a scalar value to be
6902 incorporated into a <style> section. Style definitions in B<-code>
6903 override similarly-named ones in B<-src>, hence the name "cascading."
6905 You may also specify the type of the stylesheet by adding the optional
6906 B<-type> parameter to the hash pointed to by B<-style>. If not
6907 specified, the style defaults to 'text/css'.
6909 To refer to a style within the body of your document, add the
6910 B<-class> parameter to any HTML element:
6912 print h1({-class=>'Fancy'},'Welcome to the Party');
6914 Or define styles on the fly with the B<-style> parameter:
6916 print h1({-style=>'Color: red;'},'Welcome to Hell');
6918 You may also use the new B<span()> element to apply a style to a
6921 print span({-style=>'Color: red;'},
6922 h1('Welcome to Hell'),
6923 "Where did that handbasket get to?"
6926 Note that you must import the ":html3" definitions to have the
6927 B<span()> method available. Here's a quick and dirty example of using
6928 CSS's. See the CSS specification at
6929 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
6931 use CGI qw/:standard :html3/;
6933 #here's a stylesheet incorporated directly into the page
6943 font-family: sans-serif;
6949 print start_html( -title=>'CGI with Style',
6950 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
6953 print h1('CGI with Style'),
6955 "Better read the cascading style sheet spec before playing with this!"),
6956 span({-style=>'color: magenta'},
6957 "Look Mom, no hands!",
6963 Pass an array reference to B<-code> or B<-src> in order to incorporate
6964 multiple stylesheets into your document.
6966 Should you wish to incorporate a verbatim stylesheet that includes
6967 arbitrary formatting in the header, you may pass a -verbatim tag to
6968 the -style hash, as follows:
6970 print start_html (-STYLE => {-verbatim => '@import
6971 url("/server-common/css/'.$cssFile.'");',
6972 -src => '/server-common/css/core.css'});
6976 This will generate an HTML header that contains this:
6978 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
6979 <style type="text/css">
6980 @import url("/server-common/css/main.css");
6983 Any additional arguments passed in the -style value will be
6984 incorporated into the <link> tag. For example:
6986 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
6991 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
6992 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
6996 To make more complicated <link> tags, use the Link() function
6997 and pass it to start_html() in the -head argument, as in:
6999 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
7000 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
7001 print start_html({-head=>\@h})
7005 If you are running the script from the command line or in the perl
7006 debugger, you can pass the script a list of keywords or
7007 parameter=value pairs on the command line or from standard input (you
7008 don't have to worry about tricking your script into reading from
7009 environment variables). You can pass keywords like this:
7011 your_script.pl keyword1 keyword2 keyword3
7015 your_script.pl keyword1+keyword2+keyword3
7019 your_script.pl name1=value1 name2=value2
7023 your_script.pl name1=value1&name2=value2
7025 To turn off this feature, use the -no_debug pragma.
7027 To test the POST method, you may enable full debugging with the -debug
7028 pragma. This will allow you to feed newline-delimited name=value
7029 pairs to the script on standard input.
7031 When debugging, you can use quotes and backslashes to escape
7032 characters in the familiar shell manner, letting you place
7033 spaces and other funny characters in your parameter=value
7036 your_script.pl "name1='I am a long value'" "name2=two\ words"
7038 Finally, you can set the path info for the script by prefixing the first
7039 name/value parameter with the path followed by a question mark (?):
7041 your_script.pl /your/path/here?name1=value1&name2=value2
7043 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
7045 The Dump() method produces a string consisting of all the query's
7046 name/value pairs formatted nicely as a nested list. This is useful
7047 for debugging purposes:
7052 Produces something that looks like:
7066 As a shortcut, you can interpolate the entire CGI object into a string
7067 and it will be replaced with the a nice HTML dump shown above:
7070 print "<h2>Current Values</h2> $query\n";
7072 =head1 FETCHING ENVIRONMENT VARIABLES
7074 Some of the more useful environment variables can be fetched
7075 through this interface. The methods are as follows:
7081 Return a list of MIME types that the remote browser accepts. If you
7082 give this method a single argument corresponding to a MIME type, as in
7083 Accept('text/html'), it will return a floating point value
7084 corresponding to the browser's preference for this type from 0.0
7085 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
7086 list are handled correctly.
7088 Note that the capitalization changed between version 2.43 and 2.44 in
7089 order to avoid conflict with Perl's accept() function.
7091 =item B<raw_cookie()>
7093 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
7094 Netscape browsers version 1.1 and higher, and all versions of Internet
7095 Explorer. Cookies have a special format, and this method call just
7096 returns the raw form (?cookie dough). See cookie() for ways of
7097 setting and retrieving cooked cookies.
7099 Called with no parameters, raw_cookie() returns the packed cookie
7100 structure. You can separate it into individual cookies by splitting
7101 on the character sequence "; ". Called with the name of a cookie,
7102 retrieves the B<unescaped> form of the cookie. You can use the
7103 regular cookie() method to get the names, or use the raw_fetch()
7104 method from the CGI::Cookie module.
7106 =item B<user_agent()>
7108 Returns the HTTP_USER_AGENT variable. If you give
7109 this method a single argument, it will attempt to
7110 pattern match on it, allowing you to do something
7111 like user_agent(netscape);
7113 =item B<path_info()>
7115 Returns additional path information from the script URL.
7116 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
7117 path_info() returning "/additional/stuff".
7119 NOTE: The Microsoft Internet Information Server
7120 is broken with respect to additional path information. If
7121 you use the Perl DLL library, the IIS server will attempt to
7122 execute the additional path information as a Perl script.
7123 If you use the ordinary file associations mapping, the
7124 path information will be present in the environment,
7125 but incorrect. The best thing to do is to avoid using additional
7126 path information in CGI scripts destined for use with IIS.
7128 =item B<path_translated()>
7130 As per path_info() but returns the additional
7131 path information translated into a physical path, e.g.
7132 "/usr/local/etc/httpd/htdocs/additional/stuff".
7134 The Microsoft IIS is broken with respect to the translated
7137 =item B<remote_host()>
7139 Returns either the remote host name or IP address.
7140 if the former is unavailable.
7142 =item B<script_name()>
7143 Return the script name as a partial URL, for self-refering
7148 Return the URL of the page the browser was viewing
7149 prior to fetching your script. Not available for all
7152 =item B<auth_type ()>
7154 Return the authorization/verification method in use for this
7157 =item B<server_name ()>
7159 Returns the name of the server, usually the machine's host
7162 =item B<virtual_host ()>
7164 When using virtual hosts, returns the name of the host that
7165 the browser attempted to contact
7167 =item B<server_port ()>
7169 Return the port that the server is listening on.
7171 =item B<virtual_port ()>
7173 Like server_port() except that it takes virtual hosts into account.
7174 Use this when running with virtual hosts.
7176 =item B<server_software ()>
7178 Returns the server software and version number.
7180 =item B<remote_user ()>
7182 Return the authorization/verification name used for user
7183 verification, if this script is protected.
7185 =item B<user_name ()>
7187 Attempt to obtain the remote user's name, using a variety of different
7188 techniques. This only works with older browsers such as Mosaic.
7189 Newer browsers do not report the user name for privacy reasons!
7191 =item B<request_method()>
7193 Returns the method used to access your script, usually
7194 one of 'POST', 'GET' or 'HEAD'.
7196 =item B<content_type()>
7198 Returns the content_type of data submitted in a POST, generally
7199 multipart/form-data or application/x-www-form-urlencoded
7203 Called with no arguments returns the list of HTTP environment
7204 variables, including such things as HTTP_USER_AGENT,
7205 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
7206 like-named HTTP header fields in the request. Called with the name of
7207 an HTTP header field, returns its value. Capitalization and the use
7208 of hyphens versus underscores are not significant.
7210 For example, all three of these examples are equivalent:
7212 $requested_language = http('Accept-language');
7213 $requested_language = http('Accept_language');
7214 $requested_language = http('HTTP_ACCEPT_LANGUAGE');
7218 The same as I<http()>, but operates on the HTTPS environment variables
7219 present when the SSL protocol is in effect. Can be used to determine
7220 whether SSL is turned on.
7224 =head1 USING NPH SCRIPTS
7226 NPH, or "no-parsed-header", scripts bypass the server completely by
7227 sending the complete HTTP header directly to the browser. This has
7228 slight performance benefits, but is of most use for taking advantage
7229 of HTTP extensions that are not directly supported by your server,
7230 such as server push and PICS headers.
7232 Servers use a variety of conventions for designating CGI scripts as
7233 NPH. Many Unix servers look at the beginning of the script's name for
7234 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
7235 Internet Information Server, in contrast, try to decide whether a
7236 program is an NPH script by examining the first line of script output.
7239 CGI.pm supports NPH scripts with a special NPH mode. When in this
7240 mode, CGI.pm will output the necessary extra header information when
7241 the header() and redirect() methods are
7244 The Microsoft Internet Information Server requires NPH mode. As of
7245 version 2.30, CGI.pm will automatically detect when the script is
7246 running under IIS and put itself into this mode. You do not need to
7247 do this manually, although it won't hurt anything if you do. However,
7248 note that if you have applied Service Pack 6, much of the
7249 functionality of NPH scripts, including the ability to redirect while
7250 setting a cookie, b<do not work at all> on IIS without a special patch
7252 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
7253 Non-Parsed Headers Stripped From CGI Applications That Have nph-
7258 =item In the B<use> statement
7260 Simply add the "-nph" pragmato the list of symbols to be imported into
7263 use CGI qw(:standard -nph)
7265 =item By calling the B<nph()> method:
7267 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
7271 =item By using B<-nph> parameters
7273 in the B<header()> and B<redirect()> statements:
7275 print header(-nph=>1);
7281 CGI.pm provides four simple functions for producing multipart
7282 documents of the type needed to implement server push. These
7283 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
7284 import these into your namespace, you must import the ":push" set.
7285 You are also advised to put the script into NPH mode and to set $| to
7286 1 to avoid buffering problems.
7288 Here is a simple script that demonstrates server push:
7290 #!/usr/local/bin/perl
7291 use CGI qw/:push -nph/;
7293 print multipart_init(-boundary=>'----here we go!');
7295 print multipart_start(-type=>'text/plain'),
7296 "The current time is ",scalar(localtime),"\n";
7298 print multipart_end;
7300 print multipart_final;
7305 This script initializes server push by calling B<multipart_init()>.
7306 It then enters a loop in which it begins a new multipart section by
7307 calling B<multipart_start()>, prints the current local time,
7308 and ends a multipart section with B<multipart_end()>. It then sleeps
7309 a second, and begins again. On the final iteration, it ends the
7310 multipart section with B<multipart_final()> rather than with
7315 =item multipart_init()
7317 multipart_init(-boundary=>$boundary);
7319 Initialize the multipart system. The -boundary argument specifies
7320 what MIME boundary string to use to separate parts of the document.
7321 If not provided, CGI.pm chooses a reasonable boundary for you.
7323 =item multipart_start()
7325 multipart_start(-type=>$type)
7327 Start a new part of the multipart document using the specified MIME
7328 type. If not specified, text/html is assumed.
7330 =item multipart_end()
7334 End a part. You must remember to call multipart_end() once for each
7335 multipart_start(), except at the end of the last part of the multipart
7336 document when multipart_final() should be called instead of multipart_end().
7338 =item multipart_final()
7342 End all parts. You should call multipart_final() rather than
7343 multipart_end() at the end of the last part of the multipart document.
7347 Users interested in server push applications should also have a look
7348 at the CGI::Push module.
7350 Only Netscape Navigator supports server push. Internet Explorer
7353 =head1 Avoiding Denial of Service Attacks
7355 A potential problem with CGI.pm is that, by default, it attempts to
7356 process form POSTings no matter how large they are. A wily hacker
7357 could attack your site by sending a CGI script a huge POST of many
7358 megabytes. CGI.pm will attempt to read the entire POST into a
7359 variable, growing hugely in size until it runs out of memory. While
7360 the script attempts to allocate the memory the system may slow down
7361 dramatically. This is a form of denial of service attack.
7363 Another possible attack is for the remote user to force CGI.pm to
7364 accept a huge file upload. CGI.pm will accept the upload and store it
7365 in a temporary directory even if your script doesn't expect to receive
7366 an uploaded file. CGI.pm will delete the file automatically when it
7367 terminates, but in the meantime the remote user may have filled up the
7368 server's disk space, causing problems for other programs.
7370 The best way to avoid denial of service attacks is to limit the amount
7371 of memory, CPU time and disk space that CGI scripts can use. Some Web
7372 servers come with built-in facilities to accomplish this. In other
7373 cases, you can use the shell I<limit> or I<ulimit>
7374 commands to put ceilings on CGI resource usage.
7377 CGI.pm also has some simple built-in protections against denial of
7378 service attacks, but you must activate them before you can use them.
7379 These take the form of two global variables in the CGI name space:
7383 =item B<$CGI::POST_MAX>
7385 If set to a non-negative integer, this variable puts a ceiling
7386 on the size of POSTings, in bytes. If CGI.pm detects a POST
7387 that is greater than the ceiling, it will immediately exit with an error
7388 message. This value will affect both ordinary POSTs and
7389 multipart POSTs, meaning that it limits the maximum size of file
7390 uploads as well. You should set this to a reasonably high
7391 value, such as 1 megabyte.
7393 =item B<$CGI::DISABLE_UPLOADS>
7395 If set to a non-zero value, this will disable file uploads
7396 completely. Other fill-out form values will work as usual.
7400 You can use these variables in either of two ways.
7404 =item B<1. On a script-by-script basis>
7406 Set the variable at the top of the script, right after the "use" statement:
7408 use CGI qw/:standard/;
7409 use CGI::Carp 'fatalsToBrowser';
7410 $CGI::POST_MAX=1024 * 100; # max 100K posts
7411 $CGI::DISABLE_UPLOADS = 1; # no uploads
7413 =item B<2. Globally for all scripts>
7415 Open up CGI.pm, find the definitions for $POST_MAX and
7416 $DISABLE_UPLOADS, and set them to the desired values. You'll
7417 find them towards the top of the file in a subroutine named
7418 initialize_globals().
7422 An attempt to send a POST larger than $POST_MAX bytes will cause
7423 I<param()> to return an empty CGI parameter list. You can test for
7424 this event by checking I<cgi_error()>, either after you create the CGI
7425 object or, if you are using the function-oriented interface, call
7426 <param()> for the first time. If the POST was intercepted, then
7427 cgi_error() will return the message "413 POST too large".
7429 This error message is actually defined by the HTTP protocol, and is
7430 designed to be returned to the browser as the CGI script's status
7433 $uploaded_file = param('upload');
7434 if (!$uploaded_file && cgi_error()) {
7435 print header(-status=>cgi_error());
7439 However it isn't clear that any browser currently knows what to do
7440 with this status code. It might be better just to create an
7441 HTML page that warns the user of the problem.
7443 =head1 COMPATIBILITY WITH CGI-LIB.PL
7445 To make it easier to port existing programs that use cgi-lib.pl the
7446 compatibility routine "ReadParse" is provided. Porting is simple:
7449 require "cgi-lib.pl";
7451 print "The value of the antique is $in{antique}.\n";
7456 print "The value of the antique is $in{antique}.\n";
7458 CGI.pm's ReadParse() routine creates a tied variable named %in,
7459 which can be accessed to obtain the query variables. Like
7460 ReadParse, you can also provide your own variable. Infrequently
7461 used features of ReadParse, such as the creation of @in and $in
7462 variables, are not supported.
7464 Once you use ReadParse, you can retrieve the query object itself
7468 print textfield(-name=>'wow',
7469 -value=>'does this really work?');
7471 This allows you to start using the more interesting features
7472 of CGI.pm without rewriting your old scripts from scratch.
7474 =head1 AUTHOR INFORMATION
7476 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
7478 This library is free software; you can redistribute it and/or modify
7479 it under the same terms as Perl itself.
7481 Address bug reports and comments to: lstein@cshl.org. When sending
7482 bug reports, please provide the version of CGI.pm, the version of
7483 Perl, the name and version of your Web server, and the name and
7484 version of the operating system you are using. If the problem is even
7485 remotely browser dependent, please provide information about the
7486 affected browers as well.
7490 Thanks very much to:
7494 =item Matt Heffron (heffron@falstaff.css.beckman.com)
7496 =item James Taylor (james.taylor@srs.gov)
7498 =item Scott Anguish <sanguish@digifix.com>
7500 =item Mike Jewell (mlj3u@virginia.edu)
7502 =item Timothy Shimmin (tes@kbs.citri.edu.au)
7504 =item Joergen Haegg (jh@axis.se)
7506 =item Laurent Delfosse (delfosse@delfosse.com)
7508 =item Richard Resnick (applepi1@aol.com)
7510 =item Craig Bishop (csb@barwonwater.vic.gov.au)
7512 =item Tony Curtis (tc@vcpc.univie.ac.at)
7514 =item Tim Bunce (Tim.Bunce@ig.co.uk)
7516 =item Tom Christiansen (tchrist@convex.com)
7518 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
7520 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
7522 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
7524 =item Stephen Dahmen (joyfire@inxpress.net)
7526 =item Ed Jordan (ed@fidalgo.net)
7528 =item David Alan Pisoni (david@cnation.com)
7530 =item Doug MacEachern (dougm@opengroup.org)
7532 =item Robin Houston (robin@oneworld.org)
7534 =item ...and many many more...
7536 for suggestions and bug fixes.
7540 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
7543 #!/usr/local/bin/perl
7545 use CGI ':standard';
7548 print start_html("Example CGI.pm Form");
7549 print "<h1> Example CGI.pm Form</h1>\n";
7557 print "<em>What's your name?</em><br>";
7558 print textfield('name');
7559 print checkbox('Not my real name');
7561 print "<p><em>Where can you find English Sparrows?</em><br>";
7562 print checkbox_group(
7563 -name=>'Sparrow locations',
7564 -values=>[England,France,Spain,Asia,Hoboken],
7566 -defaults=>[England,Asia]);
7568 print "<p><em>How far can they fly?</em><br>",
7571 -values=>['10 ft','1 mile','10 miles','real far'],
7572 -default=>'1 mile');
7574 print "<p><em>What's your favorite color?</em> ";
7575 print popup_menu(-name=>'Color',
7576 -values=>['black','brown','red','yellow'],
7579 print hidden('Reference','Monty Python and the Holy Grail');
7581 print "<p><em>What have you got there?</em><br>";
7582 print scrolling_list(
7583 -name=>'possessions',
7584 -values=>['A Coconut','A Grail','An Icon',
7585 'A Sword','A Ticket'],
7589 print "<p><em>Any parting comments?</em><br>";
7590 print textarea(-name=>'Comments',
7595 print submit('Action','Shout');
7596 print submit('Action','Scream');
7604 print "<h2>Here are the current settings in this form</h2>";
7606 foreach $key (param) {
7607 print "<strong>$key</strong> -> ";
7608 @values = param($key);
7609 print join(", ",@values),"<br>\n";
7616 <address>Lincoln D. Stein</address><br>
7617 <a href="/">Home Page</a>
7627 L<CGI::Carp>, L<CGI::Fast>, L<CGI::Pretty>