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.125 2003/06/16 18:54:19 lstein Exp $';
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);
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);
42 $MOD_PERL = 0; # no mod_perl by default
44 # >>>>> Here are some globals that you might want to adjust <<<<<<
45 sub initialize_globals {
46 # Set this to 1 to enable copious autoloader debugging messages
49 # Set this to 1 to generate XTML-compatible output
52 # Change this to the preferred DTD to print in start_html()
53 # or use default_dtd('text of DTD to use');
54 $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN',
55 'http://www.w3.org/TR/html4/loose.dtd' ] ;
57 # Set this to 1 to enable NOSTICKY scripts
59 # 1) use CGI qw(-nosticky)
60 # 2) $CGI::nosticky(1)
63 # Set this to 1 to enable NPH scripts
67 # 3) print header(-nph=>1)
70 # Set this to 1 to enable debugging from @ARGV
71 # Set to 2 to enable debugging from STDIN
74 # Set this to 1 to make the temporary files created
75 # during file uploads safe from prying eyes
77 # 1) use CGI qw(:private_tempfiles)
78 # 2) CGI::private_tempfiles(1);
79 $PRIVATE_TEMPFILES = 0;
81 # Set this to 1 to cause files uploaded in multipart documents
82 # to be closed, instead of caching the file handle
84 # 1) use CGI qw(:close_upload_files)
85 # 2) $CGI::close_upload_files(1);
86 # Uploads with many files run out of file handles.
87 # Also, for performance, since the file is already on disk,
88 # it can just be renamed, instead of read and written.
89 $CLOSE_UPLOAD_FILES = 0;
91 # Set this to a positive value to limit the size of a POSTing
92 # to a certain number of bytes:
95 # Change this to 1 to disable uploads entirely:
98 # Automatically determined -- don't change
101 # Change this to 1 to suppress redundant HTTP headers
104 # separate the name=value pairs by semicolons rather than ampersands
105 $USE_PARAM_SEMICOLONS = 1;
107 # Do not include undefined params parsed from query string
108 # use CGI qw(-no_undef_params);
109 $NO_UNDEF_PARAMS = 0;
111 # Other globals that you shouldn't worry about.
116 undef $QUERY_CHARSET;
117 undef %QUERY_FIELDNAMES;
119 # prevent complaints by mod_perl
123 # ------------------ START OF THE LIBRARY ------------
126 initialize_globals();
128 # FIGURE OUT THE OS WE'RE RUNNING UNDER
129 # Some systems support the $^O variable. If not
130 # available then require() the Config library
134 $OS = $Config::Config{'osname'};
137 if ($OS =~ /^MSWin/i) {
139 } elsif ($OS =~ /^VMS/i) {
141 } elsif ($OS =~ /^dos/i) {
143 } elsif ($OS =~ /^MacOS/i) {
145 } elsif ($OS =~ /^os2/i) {
147 } elsif ($OS =~ /^epoc/i) {
149 } elsif ($OS =~ /^cygwin/i) {
155 # Some OS logic. Binary mode enabled on DOS, NT and VMS
156 $needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin|CYGWIN)/;
158 # This is the default class for the CGI object to use when all else fails.
159 $DefaultClass = 'CGI' unless defined $CGI::DefaultClass;
161 # This is where to look for autoloaded routines.
162 $AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;
164 # The path separator is a slash, backslash or semicolon, depending
167 UNIX => '/', OS2 => '\\', EPOC => '/', CYGWIN => '/',
168 WINDOWS => '\\', DOS => '\\', MACINTOSH => ':', VMS => '/'
171 # This no longer seems to be necessary
172 # Turn on NPH scripts by default when running under IIS server!
173 # $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
174 $IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
176 # Turn on special checking for Doug MacEachern's modperl
177 if (exists $ENV{MOD_PERL}) {
178 eval "require mod_perl";
179 # mod_perl handlers may run system() on scripts using CGI.pm;
180 # Make sure so we don't get fooled by inherited $ENV{MOD_PERL}
181 if (defined $mod_perl::VERSION) {
182 if ($mod_perl::VERSION >= 1.99) {
184 require Apache::RequestRec;
185 require Apache::RequestUtil;
194 # Turn on special checking for ActiveState's PerlEx
195 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
197 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
198 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
199 # and sometimes CR). The most popular VMS web server
200 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
201 # use ASCII, so \015\012 means something different. I find this all
203 $EBCDIC = "\t" ne "\011";
212 if ($needs_binmode) {
213 $CGI::DefaultClass->binmode(main::STDOUT);
214 $CGI::DefaultClass->binmode(main::STDIN);
215 $CGI::DefaultClass->binmode(main::STDERR);
219 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
220 tt u i b blockquote pre img a address cite samp dfn html head
221 base body Link nextid title meta kbd start_html end_html
222 input Select option comment charset escapeHTML/],
223 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
224 embed basefont style span layer ilayer font frameset frame script small big Area Map/],
225 ':html4'=>[qw/abbr acronym bdo col colgroup del fieldset iframe
226 ins label legend noframes noscript object optgroup Q
228 ':netscape'=>[qw/blink fontsize center/],
229 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
230 submit reset defaults radio_group popup_menu button autoEscape
231 scrolling_list image_button start_form end_form startform endform
232 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
233 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
234 raw_cookie request_method query_string Accept user_agent remote_host content_type
235 remote_addr referer server_name server_software server_port server_protocol
236 virtual_host remote_ident auth_type http
237 save_parameters restore_parameters param_fetch
238 remote_user user_name header redirect import_names put
239 Delete Delete_all url_param cgi_error/],
240 ':ssl' => [qw/https/],
241 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
242 ':html' => [qw/:html2 :html3 :html4 :netscape/],
243 ':standard' => [qw/:html2 :html3 :html4 :form :cgi/],
244 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
245 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal :html4/]
248 # to import symbols into caller
252 # This causes modules to clash.
256 $self->_setup_symbols(@_);
257 my ($callpack, $callfile, $callline) = caller;
259 # To allow overriding, search through the packages
260 # Till we find one in which the correct subroutine is defined.
261 my @packages = ($self,@{"$self\:\:ISA"});
262 foreach $sym (keys %EXPORT) {
264 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
265 foreach $pck (@packages) {
266 if (defined(&{"$pck\:\:$sym"})) {
271 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
277 $pack->_setup_symbols('-compile',@_);
282 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
284 return ($tag) unless $EXPORT_TAGS{$tag};
285 foreach (@{$EXPORT_TAGS{$tag}}) {
286 push(@r,&expand_tags($_));
292 # The new routine. This will check the current environment
293 # for an existing query string, and initialize itself, if so.
296 my($class,@initializer) = @_;
298 bless $self,ref $class || $class || $DefaultClass;
299 if (ref($initializer[0])
300 && (UNIVERSAL::isa($initializer[0],'Apache')
302 UNIVERSAL::isa($initializer[0],'Apache::RequestRec')
304 $self->r(shift @initializer);
307 $self->r(Apache->request) unless $self->r;
309 if ($MOD_PERL == 1) {
310 $r->register_cleanup(\&CGI::_reset_globals);
313 # XXX: once we have the new API
314 # will do a real PerlOptions -SetupEnv check
315 $r->subprocess_env unless exists $ENV{REQUEST_METHOD};
316 $r->pool->cleanup_register(\&CGI::_reset_globals);
320 $self->_reset_globals if $PERLEX;
321 $self->init(@initializer);
325 # We provide a DESTROY method so that the autoloader
326 # doesn't bother trying to find it.
331 my $r = $self->{'.r'};
332 $self->{'.r'} = shift if @_;
337 # Returns the value(s)of a named parameter.
338 # If invoked in a list context, returns the
339 # entire list. Otherwise returns the first
340 # member of the list.
341 # If name is not provided, return a list of all
342 # the known parameters names available.
343 # If more than one argument is provided, the
344 # second and subsequent arguments are used to
345 # set the value of the parameter.
348 my($self,@p) = self_or_default(@_);
349 return $self->all_parameters unless @p;
350 my($name,$value,@other);
352 # For compatibility between old calling style and use_named_parameters() style,
353 # we have to special case for a single parameter present.
355 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
358 if (substr($p[0],0,1) eq '-') {
359 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
361 foreach ($value,@other) {
362 push(@values,$_) if defined($_);
365 # If values is provided, then we set it.
367 $self->add_parameter($name);
368 $self->{$name}=[@values];
374 return unless defined($name) && $self->{$name};
375 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
378 sub self_or_default {
379 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
380 unless (defined($_[0]) &&
381 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
383 $Q = $CGI::DefaultClass->new unless defined($Q);
386 return wantarray ? @_ : $Q;
390 local $^W=0; # prevent a warning
391 if (defined($_[0]) &&
392 (substr(ref($_[0]),0,3) eq 'CGI'
393 || UNIVERSAL::isa($_[0],'CGI'))) {
396 return ($DefaultClass,@_);
400 ########################################
401 # THESE METHODS ARE MORE OR LESS PRIVATE
402 # GO TO THE __DATA__ SECTION TO SEE MORE
404 ########################################
406 # Initialize the query object from the environment.
407 # If a parameter list is found, this object will be set
408 # to an associative array in which parameter names are keys
409 # and the values are stored as lists
410 # If a keyword list is found, this method creates a bogus
411 # parameter list with the single parameter 'keywords'.
415 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
417 my $initializer = shift; # for backward compatibility
420 # set autoescaping on by default
421 $self->{'escape'} = 1;
423 # if we get called more than once, we want to initialize
424 # ourselves from the original query (which may be gone
425 # if it was read from STDIN originally.)
426 if (defined(@QUERY_PARAM) && !defined($initializer)) {
427 foreach (@QUERY_PARAM) {
428 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
430 $self->charset($QUERY_CHARSET);
431 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
435 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
436 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
438 $fh = to_filehandle($initializer) if $initializer;
440 # set charset to the safe ISO-8859-1
441 $self->charset('ISO-8859-1');
445 # avoid unreasonably large postings
446 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
447 # quietly read and discard the post
449 my $max = $content_length;
450 while ($max > 0 && (my $bytes = read(STDIN,$buffer,$max < 10000 ? $max : 10000))) {
453 $self->cgi_error("413 Request entity too large");
457 # Process multipart postings, but only if the initializer is
460 && defined($ENV{'CONTENT_TYPE'})
461 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
462 && !defined($initializer)
464 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
465 $self->read_multipart($boundary,$content_length);
469 # If initializer is defined, then read parameters
471 if (defined($initializer)) {
472 if (UNIVERSAL::isa($initializer,'CGI')) {
473 $query_string = $initializer->query_string;
476 if (ref($initializer) && ref($initializer) eq 'HASH') {
477 foreach (keys %$initializer) {
478 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
483 if (defined($fh) && ($fh ne '')) {
489 # massage back into standard format
490 if ("@lines" =~ /=/) {
491 $query_string=join("&",@lines);
493 $query_string=join("+",@lines);
498 # last chance -- treat it as a string
499 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
500 $query_string = $initializer;
505 # If method is GET or HEAD, fetch the query from
507 if ($meth=~/^(GET|HEAD)$/) {
509 $query_string = $self->r->args;
511 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
512 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
517 if ($meth eq 'POST') {
518 $self->read_from_client(\*STDIN,\$query_string,$content_length,0)
519 if $content_length > 0;
520 # Some people want to have their cake and eat it too!
521 # Uncomment this line to have the contents of the query string
522 # APPENDED to the POST data.
523 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
527 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
528 # Check the command line and then the standard input for data.
529 # We use the shellwords package in order to behave the way that
530 # UN*X programmers expect.
531 $query_string = read_from_cmdline() if $DEBUG;
534 # YL: Begin Change for XML handler 10/19/2001
536 && defined($ENV{'CONTENT_TYPE'})
537 && $ENV{'CONTENT_TYPE'} !~ m|^application/x-www-form-urlencoded|
538 && $ENV{'CONTENT_TYPE'} !~ m|^multipart/form-data| ) {
539 my($param) = 'POSTDATA' ;
540 $self->add_parameter($param) ;
541 push (@{$self->{$param}},$query_string);
542 undef $query_string ;
544 # YL: End Change for XML handler 10/19/2001
546 # We now have the query string in hand. We do slightly
547 # different things for keyword lists and parameter lists.
548 if (defined $query_string && length $query_string) {
549 if ($query_string =~ /[&=;]/) {
550 $self->parse_params($query_string);
552 $self->add_parameter('keywords');
553 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
557 # Special case. Erase everything if there is a field named
559 if ($self->param('.defaults')) {
563 # Associative array containing our defined fieldnames
564 $self->{'.fieldnames'} = {};
565 foreach ($self->param('.cgifields')) {
566 $self->{'.fieldnames'}->{$_}++;
569 # Clear out our default submission button flag if present
570 $self->delete('.submit');
571 $self->delete('.cgifields');
573 $self->save_request unless defined $initializer;
576 # FUNCTIONS TO OVERRIDE:
577 # Turn a string into a filehandle
580 return undef unless $thingy;
581 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
582 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
585 while (my $package = caller($caller++)) {
586 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
587 return $tmp if defined(fileno($tmp));
593 # send output to the browser
595 my($self,@p) = self_or_default(@_);
599 # print to standard output (for overriding in mod_perl)
605 # get/set last cgi_error
607 my ($self,$err) = self_or_default(@_);
608 $self->{'.cgi_error'} = $err if defined $err;
609 return $self->{'.cgi_error'};
614 # We're going to play with the package globals now so that if we get called
615 # again, we initialize ourselves in exactly the same way. This allows
616 # us to have several of these objects.
617 @QUERY_PARAM = $self->param; # save list of parameters
618 foreach (@QUERY_PARAM) {
619 next unless defined $_;
620 $QUERY_PARAM{$_}=$self->{$_};
622 $QUERY_CHARSET = $self->charset;
623 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
627 my($self,$tosplit) = @_;
628 my(@pairs) = split(/[&;]/,$tosplit);
631 ($param,$value) = split('=',$_,2);
632 next unless defined $param;
633 next if $NO_UNDEF_PARAMS and not defined $value;
634 $value = '' unless defined $value;
635 $param = unescape($param);
636 $value = unescape($value);
637 $self->add_parameter($param);
638 push (@{$self->{$param}},$value);
644 return unless defined $param;
645 push (@{$self->{'.parameters'}},$param)
646 unless defined($self->{$param});
651 return () unless defined($self) && $self->{'.parameters'};
652 return () unless @{$self->{'.parameters'}};
653 return @{$self->{'.parameters'}};
656 # put a filehandle into binary mode (DOS)
658 CORE::binmode($_[1]);
662 my ($self,$tagname) = @_;
665 my (\$q,\$a,\@rest) = self_or_default(\@_);
667 if (ref(\$a) && ref(\$a) eq 'HASH') {
668 my(\@attr) = make_attributes(\$a,\$q->{'escape'});
669 \$attr = " \@attr" if \@attr;
671 unshift \@rest,\$a if defined \$a;
674 if ($tagname=~/start_(\w+)/i) {
675 $func .= qq! return "<\L$1\E\$attr>";} !;
676 } elsif ($tagname=~/end_(\w+)/i) {
677 $func .= qq! return "<\L/$1\E>"; } !;
680 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@rest;
681 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
682 my \@result = map { "\$tag\$_\$untag" }
683 (ref(\$rest[0]) eq 'ARRAY') ? \@{\$rest[0]} : "\@rest";
691 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
692 my $func = &_compile;
697 my($func) = $AUTOLOAD;
698 my($pack,$func_name);
700 local($1,$2); # this fixes an obscure variable suicide problem.
701 $func=~/(.+)::([^:]+)$/;
702 ($pack,$func_name) = ($1,$2);
703 $pack=~s/::SUPER$//; # fix another obscure problem
704 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
705 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
707 my($sub) = \%{"$pack\:\:SUBS"};
709 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
710 eval "package $pack; $$auto";
711 croak("$AUTOLOAD: $@") if $@;
712 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
714 my($code) = $sub->{$func_name};
716 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
718 (my $base = $func_name) =~ s/^(start_|end_)//i;
719 if ($EXPORT{':any'} ||
722 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
723 && $EXPORT_OK{$base}) {
724 $code = $CGI::DefaultClass->_make_tag_func($func_name);
727 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
728 eval "package $pack; $code";
731 croak("$AUTOLOAD: $@");
734 CORE::delete($sub->{$func_name}); #free storage
735 return "$pack\:\:$func_name";
741 return '' unless $value;
742 return $XHTML ? qq( selected="selected") : qq( selected);
748 return '' unless $value;
749 return $XHTML ? qq( checked="checked") : qq( checked);
752 sub _reset_globals { initialize_globals(); }
758 # to avoid reexporting unwanted variables
762 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
763 $NPH++, next if /^[:-]nph$/;
764 $NOSTICKY++, next if /^[:-]nosticky$/;
765 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
766 $DEBUG=2, next if /^[:-][Dd]ebug$/;
767 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
768 $XHTML++, next if /^[:-]xhtml$/;
769 $XHTML=0, next if /^[:-]no_?xhtml$/;
770 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
771 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
772 $CLOSE_UPLOAD_FILES++, next if /^[:-]close_upload_files$/;
773 $EXPORT{$_}++, next if /^[:-]any$/;
774 $compile++, next if /^[:-]compile$/;
775 $NO_UNDEF_PARAMS++, next if /^[:-]no_undef_params$/;
777 # This is probably extremely evil code -- to be deleted some day.
778 if (/^[-]autoload$/) {
779 my($pkg) = caller(1);
780 *{"${pkg}::AUTOLOAD"} = sub {
781 my($routine) = $AUTOLOAD;
782 $routine =~ s/^.*::/CGI::/;
788 foreach (&expand_tags($_)) {
789 tr/a-zA-Z0-9_//cd; # don't allow weird function names
793 _compile_all(keys %EXPORT) if $compile;
798 my ($self,$charset) = self_or_default(@_);
799 $self->{'.charset'} = $charset if defined $charset;
803 ###############################################################################
804 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
805 ###############################################################################
806 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
807 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
811 'URL_ENCODED'=> <<'END_OF_FUNC',
812 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
815 'MULTIPART' => <<'END_OF_FUNC',
816 sub MULTIPART { 'multipart/form-data'; }
819 'SERVER_PUSH' => <<'END_OF_FUNC',
820 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
823 'new_MultipartBuffer' => <<'END_OF_FUNC',
824 # Create a new multipart buffer
825 sub new_MultipartBuffer {
826 my($self,$boundary,$length,$filehandle) = @_;
827 return MultipartBuffer->new($self,$boundary,$length,$filehandle);
831 'read_from_client' => <<'END_OF_FUNC',
832 # Read data from a file handle
833 sub read_from_client {
834 my($self, $fh, $buff, $len, $offset) = @_;
835 local $^W=0; # prevent a warning
836 return undef unless defined($fh);
837 return read($fh, $$buff, $len, $offset);
841 'delete' => <<'END_OF_FUNC',
843 # Deletes the named parameter entirely.
846 my($self,@p) = self_or_default(@_);
847 my(@names) = rearrange([NAME],@p);
848 my @to_delete = ref($names[0]) eq 'ARRAY' ? @$names[0] : @names;
850 foreach my $name (@to_delete)
852 CORE::delete $self->{$name};
853 CORE::delete $self->{'.fieldnames'}->{$name};
856 @{$self->{'.parameters'}}=grep { !exists($to_delete{$_}) } $self->param();
857 return wantarray ? () : undef;
861 #### Method: import_names
862 # Import all parameters into the given namespace.
863 # Assumes namespace 'Q' if not specified
865 'import_names' => <<'END_OF_FUNC',
867 my($self,$namespace,$delete) = self_or_default(@_);
868 $namespace = 'Q' unless defined($namespace);
869 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
870 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
871 # can anyone find an easier way to do this?
872 foreach (keys %{"${namespace}::"}) {
873 local *symbol = "${namespace}::${_}";
879 my($param,@value,$var);
880 foreach $param ($self->param) {
881 # protect against silly names
882 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
883 $var =~ s/^(?=\d)/_/;
884 local *symbol = "${namespace}::$var";
885 @value = $self->param($param);
892 #### Method: keywords
893 # Keywords acts a bit differently. Calling it in a list context
894 # returns the list of keywords.
895 # Calling it in a scalar context gives you the size of the list.
897 'keywords' => <<'END_OF_FUNC',
899 my($self,@values) = self_or_default(@_);
900 # If values is provided, then we set it.
901 $self->{'keywords'}=[@values] if @values;
902 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
907 # These are some tie() interfaces for compatibility
908 # with Steve Brenner's cgi-lib.pl routines
909 'Vars' => <<'END_OF_FUNC',
914 return %in if wantarray;
919 # These are some tie() interfaces for compatibility
920 # with Steve Brenner's cgi-lib.pl routines
921 'ReadParse' => <<'END_OF_FUNC',
931 return scalar(keys %in);
935 'PrintHeader' => <<'END_OF_FUNC',
937 my($self) = self_or_default(@_);
938 return $self->header();
942 'HtmlTop' => <<'END_OF_FUNC',
944 my($self,@p) = self_or_default(@_);
945 return $self->start_html(@p);
949 'HtmlBot' => <<'END_OF_FUNC',
951 my($self,@p) = self_or_default(@_);
952 return $self->end_html(@p);
956 'SplitParam' => <<'END_OF_FUNC',
959 my (@params) = split ("\0", $param);
960 return (wantarray ? @params : $params[0]);
964 'MethGet' => <<'END_OF_FUNC',
966 return request_method() eq 'GET';
970 'MethPost' => <<'END_OF_FUNC',
972 return request_method() eq 'POST';
976 'TIEHASH' => <<'END_OF_FUNC',
980 if (ref($arg) && UNIVERSAL::isa($arg,'CGI')) {
983 return $Q ||= $class->new(@_);
987 'STORE' => <<'END_OF_FUNC',
992 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
993 $self->param(-name=>$tag,-value=>\@vals);
997 'FETCH' => <<'END_OF_FUNC',
999 return $_[0] if $_[1] eq 'CGI';
1000 return undef unless defined $_[0]->param($_[1]);
1001 return join("\0",$_[0]->param($_[1]));
1005 'FIRSTKEY' => <<'END_OF_FUNC',
1007 $_[0]->{'.iterator'}=0;
1008 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1012 'NEXTKEY' => <<'END_OF_FUNC',
1014 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1018 'EXISTS' => <<'END_OF_FUNC',
1020 exists $_[0]->{$_[1]};
1024 'DELETE' => <<'END_OF_FUNC',
1026 $_[0]->delete($_[1]);
1030 'CLEAR' => <<'END_OF_FUNC',
1038 # Append a new value to an existing query
1040 'append' => <<'EOF',
1043 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
1044 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
1046 $self->add_parameter($name);
1047 push(@{$self->{$name}},@values);
1049 return $self->param($name);
1053 #### Method: delete_all
1054 # Delete all parameters
1056 'delete_all' => <<'EOF',
1058 my($self) = self_or_default(@_);
1059 my @param = $self->param();
1060 $self->delete(@param);
1064 'Delete' => <<'EOF',
1066 my($self,@p) = self_or_default(@_);
1071 'Delete_all' => <<'EOF',
1073 my($self,@p) = self_or_default(@_);
1074 $self->delete_all(@p);
1078 #### Method: autoescape
1079 # If you want to turn off the autoescaping features,
1080 # call this method with undef as the argument
1081 'autoEscape' => <<'END_OF_FUNC',
1083 my($self,$escape) = self_or_default(@_);
1084 my $d = $self->{'escape'};
1085 $self->{'escape'} = $escape;
1091 #### Method: version
1092 # Return the current version
1094 'version' => <<'END_OF_FUNC',
1100 #### Method: url_param
1101 # Return a parameter in the QUERY_STRING, regardless of
1102 # whether this was a POST or a GET
1104 'url_param' => <<'END_OF_FUNC',
1106 my ($self,@p) = self_or_default(@_);
1107 my $name = shift(@p);
1108 return undef unless exists($ENV{QUERY_STRING});
1109 unless (exists($self->{'.url_param'})) {
1110 $self->{'.url_param'}={}; # empty hash
1111 if ($ENV{QUERY_STRING} =~ /=/) {
1112 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
1115 ($param,$value) = split('=',$_,2);
1116 $param = unescape($param);
1117 $value = unescape($value);
1118 push(@{$self->{'.url_param'}->{$param}},$value);
1121 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1124 return keys %{$self->{'.url_param'}} unless defined($name);
1125 return () unless $self->{'.url_param'}->{$name};
1126 return wantarray ? @{$self->{'.url_param'}->{$name}}
1127 : $self->{'.url_param'}->{$name}->[0];
1132 # Returns a string in which all the known parameter/value
1133 # pairs are represented as nested lists, mainly for the purposes
1136 'Dump' => <<'END_OF_FUNC',
1138 my($self) = self_or_default(@_);
1139 my($param,$value,@result);
1140 return '<ul></ul>' unless $self->param;
1141 push(@result,"<ul>");
1142 foreach $param ($self->param) {
1143 my($name)=$self->escapeHTML($param);
1144 push(@result,"<li><strong>$param</strong></li>");
1145 push(@result,"<ul>");
1146 foreach $value ($self->param($param)) {
1147 $value = $self->escapeHTML($value);
1148 $value =~ s/\n/<br />\n/g;
1149 push(@result,"<li>$value</li>");
1151 push(@result,"</ul>");
1153 push(@result,"</ul>");
1154 return join("\n",@result);
1158 #### Method as_string
1160 # synonym for "dump"
1162 'as_string' => <<'END_OF_FUNC',
1169 # Write values out to a filehandle in such a way that they can
1170 # be reinitialized by the filehandle form of the new() method
1172 'save' => <<'END_OF_FUNC',
1174 my($self,$filehandle) = self_or_default(@_);
1175 $filehandle = to_filehandle($filehandle);
1177 local($,) = ''; # set print field separator back to a sane value
1178 local($\) = ''; # set output line separator to a sane value
1179 foreach $param ($self->param) {
1180 my($escaped_param) = escape($param);
1182 foreach $value ($self->param($param)) {
1183 print $filehandle "$escaped_param=",escape("$value"),"\n";
1186 foreach (keys %{$self->{'.fieldnames'}}) {
1187 print $filehandle ".cgifields=",escape("$_"),"\n";
1189 print $filehandle "=\n"; # end of record
1194 #### Method: save_parameters
1195 # An alias for save() that is a better name for exportation.
1196 # Only intended to be used with the function (non-OO) interface.
1198 'save_parameters' => <<'END_OF_FUNC',
1199 sub save_parameters {
1201 return save(to_filehandle($fh));
1205 #### Method: restore_parameters
1206 # A way to restore CGI parameters from an initializer.
1207 # Only intended to be used with the function (non-OO) interface.
1209 'restore_parameters' => <<'END_OF_FUNC',
1210 sub restore_parameters {
1211 $Q = $CGI::DefaultClass->new(@_);
1215 #### Method: multipart_init
1216 # Return a Content-Type: style header for server-push
1217 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1219 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1220 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1222 'multipart_init' => <<'END_OF_FUNC',
1223 sub multipart_init {
1224 my($self,@p) = self_or_default(@_);
1225 my($boundary,@other) = rearrange([BOUNDARY],@p);
1226 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1227 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1228 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1229 $type = SERVER_PUSH($boundary);
1230 return $self->header(
1233 (map { split "=", $_, 2 } @other),
1234 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1239 #### Method: multipart_start
1240 # Return a Content-Type: style header for server-push, start of section
1242 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1243 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1245 'multipart_start' => <<'END_OF_FUNC',
1246 sub multipart_start {
1248 my($self,@p) = self_or_default(@_);
1249 my($type,@other) = rearrange([TYPE],@p);
1250 $type = $type || 'text/html';
1251 push(@header,"Content-Type: $type");
1253 # rearrange() was designed for the HTML portion, so we
1254 # need to fix it up a little.
1256 # Don't use \s because of perl bug 21951
1257 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1258 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1260 push(@header,@other);
1261 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1267 #### Method: multipart_end
1268 # Return a MIME boundary separator for server-push, end of section
1270 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1273 'multipart_end' => <<'END_OF_FUNC',
1275 my($self,@p) = self_or_default(@_);
1276 return $self->{'separator'};
1281 #### Method: multipart_final
1282 # Return a MIME boundary separator for server-push, end of all sections
1284 # Contributed by Andrew Benham (adsb@bigfoot.com)
1286 'multipart_final' => <<'END_OF_FUNC',
1287 sub multipart_final {
1288 my($self,@p) = self_or_default(@_);
1289 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1295 # Return a Content-Type: style header
1298 'header' => <<'END_OF_FUNC',
1300 my($self,@p) = self_or_default(@_);
1303 return undef if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1305 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,$p3p,@other) =
1306 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1307 'STATUS',['COOKIE','COOKIES'],'TARGET',
1308 'EXPIRES','NPH','CHARSET',
1309 'ATTACHMENT','P3P'],@p);
1312 if (defined $charset) {
1313 $self->charset($charset);
1315 $charset = $self->charset;
1318 # rearrange() was designed for the HTML portion, so we
1319 # need to fix it up a little.
1321 # Don't use \s because of perl bug 21951
1322 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1323 ($_ = $header) =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e;
1326 $type ||= 'text/html' unless defined($type);
1327 $type .= "; charset=$charset" if $type ne '' and $type =~ m!^text/! and $type !~ /\bcharset\b/ and $charset ne '';
1329 # Maybe future compatibility. Maybe not.
1330 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1331 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1332 push(@header,"Server: " . &server_software()) if $nph;
1334 push(@header,"Status: $status") if $status;
1335 push(@header,"Window-Target: $target") if $target;
1337 $p3p = join ' ',@$p3p if ref($p3p) eq 'ARRAY';
1338 push(@header,qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p"));
1340 # push all the cookies -- there may be several
1342 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1344 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1345 push(@header,"Set-Cookie: $cs") if $cs ne '';
1348 # if the user indicates an expiration time, then we need
1349 # both an Expires and a Date header (so that the browser is
1351 push(@header,"Expires: " . expires($expires,'http'))
1353 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1354 push(@header,"Pragma: no-cache") if $self->cache();
1355 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1356 push(@header,map {ucfirst $_} @other);
1357 push(@header,"Content-Type: $type") if $type ne '';
1358 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1359 if ($MOD_PERL and not $nph) {
1360 $self->r->send_cgi_header($header);
1369 # Control whether header() will produce the no-cache
1372 'cache' => <<'END_OF_FUNC',
1374 my($self,$new_value) = self_or_default(@_);
1375 $new_value = '' unless $new_value;
1376 if ($new_value ne '') {
1377 $self->{'cache'} = $new_value;
1379 return $self->{'cache'};
1384 #### Method: redirect
1385 # Return a Location: style header
1388 'redirect' => <<'END_OF_FUNC',
1390 my($self,@p) = self_or_default(@_);
1391 my($url,$target,$cookie,$nph,@other) = rearrange([[LOCATION,URI,URL],TARGET,['COOKIE','COOKIES'],NPH],@p);
1392 $url ||= $self->self_url;
1394 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1396 '-Status' => '302 Moved',
1399 unshift(@o,'-Target'=>$target) if $target;
1400 unshift(@o,'-Type'=>'');
1402 unshift(@unescaped,'-Cookie'=>$cookie) if $cookie;
1403 return $self->header((map {$self->unescapeHTML($_)} @o),@unescaped);
1408 #### Method: start_html
1409 # Canned HTML header
1412 # $title -> (optional) The title for this HTML document (-title)
1413 # $author -> (optional) e-mail address of the author (-author)
1414 # $base -> (optional) if set to true, will enter the BASE address of this document
1415 # for resolving relative references (-base)
1416 # $xbase -> (optional) alternative base at some remote location (-xbase)
1417 # $target -> (optional) target window to load all links into (-target)
1418 # $script -> (option) Javascript code (-script)
1419 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1420 # $meta -> (optional) Meta information tags
1421 # $head -> (optional) any other elements you'd like to incorporate into the <head> tag
1422 # (a scalar or array ref)
1423 # $style -> (optional) reference to an external style sheet
1424 # @other -> (optional) any other named parameters you'd like to incorporate into
1427 'start_html' => <<'END_OF_FUNC',
1429 my($self,@p) = &self_or_default(@_);
1430 my($title,$author,$base,$xbase,$script,$noscript,
1431 $target,$meta,$head,$style,$dtd,$lang,$encoding,@other) =
1432 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD,LANG,ENCODING],@p);
1434 $encoding = 'iso-8859-1' unless defined $encoding;
1436 # strangely enough, the title needs to be escaped as HTML
1437 # while the author needs to be escaped as a URL
1438 $title = $self->escapeHTML($title || 'Untitled Document');
1439 $author = $self->escape($author);
1440 $lang = 'en-US' unless defined $lang;
1441 my(@result,$xml_dtd);
1443 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1444 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1446 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1449 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1452 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1453 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1454 push @result,qq(<?xml version="1.0" encoding="$encoding"?>) if $xml_dtd;
1456 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1457 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t "$dtd->[1]">));
1459 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1461 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang" xml:lang="$lang"><head><title>$title</title>)
1462 : ($lang ? qq(<html lang="$lang">) : "<html>")
1463 . "<head><title>$title</title>");
1464 if (defined $author) {
1465 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1466 : "<link rev=\"made\" href=\"mailto:$author\">");
1469 if ($base || $xbase || $target) {
1470 my $href = $xbase || $self->url('-path'=>1);
1471 my $t = $target ? qq/ target="$target"/ : '';
1472 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1475 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1476 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1477 : qq(<meta name="$_" content="$meta->{$_}">)); }
1480 push(@result,ref($head) ? @$head : $head) if $head;
1482 # handle the infrequently-used -style and -script parameters
1483 push(@result,$self->_style($style)) if defined $style;
1484 push(@result,$self->_script($script)) if defined $script;
1486 # handle -noscript parameter
1487 push(@result,<<END) if $noscript;
1493 my($other) = @other ? " @other" : '';
1494 push(@result,"</head><body$other>");
1495 return join("\n",@result);
1500 # internal method for generating a CSS style section
1502 '_style' => <<'END_OF_FUNC',
1504 my ($self,$style) = @_;
1506 my $type = 'text/css';
1508 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1509 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1512 my($src,$code,$verbatim,$stype,$foo,@other) =
1513 rearrange([SRC,CODE,VERBATIM,TYPE],
1514 '-foo'=>'bar', # trick to allow dash to be omitted
1515 ref($style) eq 'ARRAY' ? @$style : %$style);
1516 $type = $stype if $stype;
1517 my $other = @other ? join ' ',@other : '';
1519 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1520 { # If it is, push a LINK tag for each one
1521 foreach $src (@$src)
1523 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1524 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)) if $src;
1528 { # Otherwise, push the single -src, if it exists.
1529 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1530 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)
1534 push(@result, "<style type=\"text/css\">\n$verbatim\n</style>");
1536 push(@result,style({'type'=>$type},"$cdata_start\n$code\n$cdata_end")) if $code;
1539 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1540 : qq(<link rel="stylesheet" type="$type" href="$src"$other>));
1546 '_script' => <<'END_OF_FUNC',
1548 my ($self,$script) = @_;
1551 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1552 foreach $script (@scripts) {
1553 my($src,$code,$language);
1554 if (ref($script)) { # script is a hash
1555 ($src,$code,$language, $type) =
1556 rearrange([SRC,CODE,LANGUAGE,TYPE],
1557 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1558 ref($script) eq 'ARRAY' ? @$script : %$script);
1559 # User may not have specified language
1560 $language ||= 'JavaScript';
1561 unless (defined $type) {
1562 $type = lc $language;
1563 # strip '1.2' from 'javascript1.2'
1564 $type =~ s/^(\D+).*$/text\/$1/;
1567 ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
1570 my $comment = '//'; # javascript by default
1571 $comment = '#' if $type=~/perl|tcl/i;
1572 $comment = "'" if $type=~/vbscript/i;
1574 my $cdata_start = "\n<!-- Hide script\n";
1575 $cdata_start .= "$comment<![CDATA[\n" if $XHTML;
1576 my $cdata_end = $XHTML ? "\n$comment]]>" : $comment;
1577 $cdata_end .= " End script hiding -->\n";
1580 push(@satts,'src'=>$src) if $src;
1581 push(@satts,'language'=>$language) unless defined $type;
1582 push(@satts,'type'=>$type);
1583 $code = "$cdata_start$code$cdata_end" if defined $code;
1584 push(@result,script({@satts},$code || ''));
1590 #### Method: end_html
1591 # End an HTML document.
1592 # Trivial method for completeness. Just returns "</body>"
1594 'end_html' => <<'END_OF_FUNC',
1596 return "</body></html>";
1601 ################################
1602 # METHODS USED IN BUILDING FORMS
1603 ################################
1605 #### Method: isindex
1606 # Just prints out the isindex tag.
1608 # $action -> optional URL of script to run
1610 # A string containing a <isindex> tag
1611 'isindex' => <<'END_OF_FUNC',
1613 my($self,@p) = self_or_default(@_);
1614 my($action,@other) = rearrange([ACTION],@p);
1615 $action = qq/ action="$action"/ if $action;
1616 my($other) = @other ? " @other" : '';
1617 return $XHTML ? "<isindex$action$other />" : "<isindex$action$other>";
1622 #### Method: startform
1625 # $method -> optional submission method to use (GET or POST)
1626 # $action -> optional URL of script to run
1627 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1628 'startform' => <<'END_OF_FUNC',
1630 my($self,@p) = self_or_default(@_);
1632 my($method,$action,$enctype,@other) =
1633 rearrange([METHOD,ACTION,ENCTYPE],@p);
1635 $method = lc($method) || 'post';
1636 $enctype = $enctype || &URL_ENCODED;
1637 unless (defined $action) {
1638 $action = $self->url(-absolute=>1,-path=>1);
1639 if (length($ENV{QUERY_STRING})>0) {
1640 $action .= "?$ENV{QUERY_STRING}";
1643 $action =~ s/\"/%22/g; # fix cross-site scripting bug reported by obscure
1644 $action = qq(action="$action");
1645 my($other) = @other ? " @other" : '';
1646 $self->{'.parametersToAdd'}={};
1647 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1652 #### Method: start_form
1653 # synonym for startform
1654 'start_form' => <<'END_OF_FUNC',
1660 'end_multipart_form' => <<'END_OF_FUNC',
1661 sub end_multipart_form {
1666 #### Method: start_multipart_form
1667 # synonym for startform
1668 'start_multipart_form' => <<'END_OF_FUNC',
1669 sub start_multipart_form {
1670 my($self,@p) = self_or_default(@_);
1671 if (defined($param[0]) && substr($param[0],0,1) eq '-') {
1673 $p{'-enctype'}=&MULTIPART;
1674 return $self->startform(%p);
1676 my($method,$action,@other) =
1677 rearrange([METHOD,ACTION],@p);
1678 return $self->startform($method,$action,&MULTIPART,@other);
1684 #### Method: endform
1686 'endform' => <<'END_OF_FUNC',
1688 my($self,@p) = self_or_default(@_);
1690 return wantarray ? ("</form>") : "\n</form>";
1692 return wantarray ? ("<div>",$self->get_fields,"</div>","</form>") :
1693 "<div>".$self->get_fields ."</div>\n</form>";
1699 #### Method: end_form
1700 # synonym for endform
1701 'end_form' => <<'END_OF_FUNC',
1708 '_textfield' => <<'END_OF_FUNC',
1710 my($self,$tag,@p) = self_or_default(@_);
1711 my($name,$default,$size,$maxlength,$override,@other) =
1712 rearrange([NAME,[DEFAULT,VALUE,VALUES],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1714 my $current = $override ? $default :
1715 (defined($self->param($name)) ? $self->param($name) : $default);
1717 $current = defined($current) ? $self->escapeHTML($current,1) : '';
1718 $name = defined($name) ? $self->escapeHTML($name) : '';
1719 my($s) = defined($size) ? qq/ size="$size"/ : '';
1720 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1721 my($other) = @other ? " @other" : '';
1722 # this entered at cristy's request to fix problems with file upload fields
1723 # and WebTV -- not sure it won't break stuff
1724 my($value) = $current ne '' ? qq(value="$current") : '';
1725 return $XHTML ? qq(<input type="$tag" name="$name" $value$s$m$other />)
1726 : qq(<input type="$tag" name="$name" $value$s$m$other>);
1730 #### Method: textfield
1732 # $name -> Name of the text field
1733 # $default -> Optional default value of the field if not
1735 # $size -> Optional width of field in characaters.
1736 # $maxlength -> Optional maximum number of characters.
1738 # A string containing a <input type="text"> field
1740 'textfield' => <<'END_OF_FUNC',
1742 my($self,@p) = self_or_default(@_);
1743 $self->_textfield('text',@p);
1748 #### Method: filefield
1750 # $name -> Name of the file upload field
1751 # $size -> Optional width of field in characaters.
1752 # $maxlength -> Optional maximum number of characters.
1754 # A string containing a <input type="file"> field
1756 'filefield' => <<'END_OF_FUNC',
1758 my($self,@p) = self_or_default(@_);
1759 $self->_textfield('file',@p);
1764 #### Method: password
1765 # Create a "secret password" entry field
1767 # $name -> Name of the field
1768 # $default -> Optional default value of the field if not
1770 # $size -> Optional width of field in characters.
1771 # $maxlength -> Optional maximum characters that can be entered.
1773 # A string containing a <input type="password"> field
1775 'password_field' => <<'END_OF_FUNC',
1776 sub password_field {
1777 my ($self,@p) = self_or_default(@_);
1778 $self->_textfield('password',@p);
1782 #### Method: textarea
1784 # $name -> Name of the text field
1785 # $default -> Optional default value of the field if not
1787 # $rows -> Optional number of rows in text area
1788 # $columns -> Optional number of columns in text area
1790 # A string containing a <textarea></textarea> tag
1792 'textarea' => <<'END_OF_FUNC',
1794 my($self,@p) = self_or_default(@_);
1796 my($name,$default,$rows,$cols,$override,@other) =
1797 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1799 my($current)= $override ? $default :
1800 (defined($self->param($name)) ? $self->param($name) : $default);
1802 $name = defined($name) ? $self->escapeHTML($name) : '';
1803 $current = defined($current) ? $self->escapeHTML($current) : '';
1804 my($r) = $rows ? qq/ rows="$rows"/ : '';
1805 my($c) = $cols ? qq/ cols="$cols"/ : '';
1806 my($other) = @other ? " @other" : '';
1807 return qq{<textarea name="$name"$r$c$other>$current</textarea>};
1813 # Create a javascript button.
1815 # $name -> (optional) Name for the button. (-name)
1816 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1817 # $onclick -> (optional) Text of the JavaScript to run when the button is
1820 # A string containing a <input type="button"> tag
1822 'button' => <<'END_OF_FUNC',
1824 my($self,@p) = self_or_default(@_);
1826 my($label,$value,$script,@other) = rearrange([NAME,[VALUE,LABEL],
1827 [ONCLICK,SCRIPT]],@p);
1829 $label=$self->escapeHTML($label);
1830 $value=$self->escapeHTML($value,1);
1831 $script=$self->escapeHTML($script);
1834 $name = qq/ name="$label"/ if $label;
1835 $value = $value || $label;
1837 $val = qq/ value="$value"/ if $value;
1838 $script = qq/ onclick="$script"/ if $script;
1839 my($other) = @other ? " @other" : '';
1840 return $XHTML ? qq(<input type="button"$name$val$script$other />)
1841 : qq(<input type="button"$name$val$script$other>);
1847 # Create a "submit query" button.
1849 # $name -> (optional) Name for the button.
1850 # $value -> (optional) Value of the button when selected (also doubles as label).
1851 # $label -> (optional) Label printed on the button(also doubles as the value).
1853 # A string containing a <input type="submit"> tag
1855 'submit' => <<'END_OF_FUNC',
1857 my($self,@p) = self_or_default(@_);
1859 my($label,$value,@other) = rearrange([NAME,[VALUE,LABEL]],@p);
1861 $label=$self->escapeHTML($label);
1862 $value=$self->escapeHTML($value,1);
1864 my($name) = ' name=".submit"' unless $NOSTICKY;
1865 $name = qq/ name="$label"/ if defined($label);
1866 $value = defined($value) ? $value : $label;
1868 $val = qq/ value="$value"/ if defined($value);
1869 my($other) = @other ? " @other" : '';
1870 return $XHTML ? qq(<input type="submit"$name$val$other />)
1871 : qq(<input type="submit"$name$val$other>);
1877 # Create a "reset" button.
1879 # $name -> (optional) Name for the button.
1881 # A string containing a <input type="reset"> tag
1883 'reset' => <<'END_OF_FUNC',
1885 my($self,@p) = self_or_default(@_);
1886 my($label,$value,@other) = rearrange(['NAME',['VALUE','LABEL']],@p);
1887 $label=$self->escapeHTML($label);
1888 $value=$self->escapeHTML($value,1);
1889 my ($name) = ' name=".reset"';
1890 $name = qq/ name="$label"/ if defined($label);
1891 $value = defined($value) ? $value : $label;
1893 $val = qq/ value="$value"/ if defined($value);
1894 my($other) = @other ? " @other" : '';
1895 return $XHTML ? qq(<input type="reset"$name$val$other />)
1896 : qq(<input type="reset"$name$val$other>);
1901 #### Method: defaults
1902 # Create a "defaults" button.
1904 # $name -> (optional) Name for the button.
1906 # A string containing a <input type="submit" name=".defaults"> tag
1908 # Note: this button has a special meaning to the initialization script,
1909 # and tells it to ERASE the current query string so that your defaults
1912 'defaults' => <<'END_OF_FUNC',
1914 my($self,@p) = self_or_default(@_);
1916 my($label,@other) = rearrange([[NAME,VALUE]],@p);
1918 $label=$self->escapeHTML($label,1);
1919 $label = $label || "Defaults";
1920 my($value) = qq/ value="$label"/;
1921 my($other) = @other ? " @other" : '';
1922 return $XHTML ? qq(<input type="submit" name=".defaults"$value$other />)
1923 : qq/<input type="submit" NAME=".defaults"$value$other>/;
1928 #### Method: comment
1929 # Create an HTML <!-- comment -->
1930 # Parameters: a string
1931 'comment' => <<'END_OF_FUNC',
1933 my($self,@p) = self_or_CGI(@_);
1934 return "<!-- @p -->";
1938 #### Method: checkbox
1939 # Create a checkbox that is not logically linked to any others.
1940 # The field value is "on" when the button is checked.
1942 # $name -> Name of the checkbox
1943 # $checked -> (optional) turned on by default if true
1944 # $value -> (optional) value of the checkbox, 'on' by default
1945 # $label -> (optional) a user-readable label printed next to the box.
1946 # Otherwise the checkbox name is used.
1948 # A string containing a <input type="checkbox"> field
1950 'checkbox' => <<'END_OF_FUNC',
1952 my($self,@p) = self_or_default(@_);
1954 my($name,$checked,$value,$label,$override,@other) =
1955 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
1957 $value = defined $value ? $value : 'on';
1959 if (!$override && ($self->{'.fieldnames'}->{$name} ||
1960 defined $self->param($name))) {
1961 $checked = grep($_ eq $value,$self->param($name)) ? $self->_checked(1) : '';
1963 $checked = $self->_checked($checked);
1965 my($the_label) = defined $label ? $label : $name;
1966 $name = $self->escapeHTML($name);
1967 $value = $self->escapeHTML($value,1);
1968 $the_label = $self->escapeHTML($the_label);
1969 my($other) = @other ? " @other" : '';
1970 $self->register_parameter($name);
1971 return $XHTML ? qq{<input type="checkbox" name="$name" value="$value"$checked$other />$the_label}
1972 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
1977 #### Method: checkbox_group
1978 # Create a list of logically-linked checkboxes.
1980 # $name -> Common name for all the check boxes
1981 # $values -> A pointer to a regular array containing the
1982 # values for each checkbox in the group.
1983 # $defaults -> (optional)
1984 # 1. If a pointer to a regular array of checkbox values,
1985 # then this will be used to decide which
1986 # checkboxes to turn on by default.
1987 # 2. If a scalar, will be assumed to hold the
1988 # value of a single checkbox in the group to turn on.
1989 # $linebreak -> (optional) Set to true to place linebreaks
1990 # between the buttons.
1991 # $labels -> (optional)
1992 # A pointer to an associative array of labels to print next to each checkbox
1993 # in the form $label{'value'}="Long explanatory label".
1994 # Otherwise the provided values are used as the labels.
1996 # An ARRAY containing a series of <input type="checkbox"> fields
1998 'checkbox_group' => <<'END_OF_FUNC',
1999 sub checkbox_group {
2000 my($self,@p) = self_or_default(@_);
2002 my($name,$values,$defaults,$linebreak,$labels,$attributes,$rows,$columns,
2003 $rowheaders,$colheaders,$override,$nolabels,@other) =
2004 rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2005 LINEBREAK,LABELS,ATTRIBUTES,ROWS,[COLUMNS,COLS],
2006 ROWHEADERS,COLHEADERS,
2007 [OVERRIDE,FORCE],NOLABELS],@p);
2009 my($checked,$break,$result,$label);
2011 my(%checked) = $self->previous_or_default($name,$defaults,$override);
2014 $break = $XHTML ? "<br />" : "<br>";
2019 $name=$self->escapeHTML($name);
2021 # Create the elements
2022 my(@elements,@values);
2024 @values = $self->_set_values_and_labels($values,\$labels,$name);
2026 my($other) = @other ? " @other" : '';
2028 $checked = $self->_checked($checked{$_});
2030 unless (defined($nolabels) && $nolabels) {
2032 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2033 $label = $self->escapeHTML($label);
2035 my $attribs = $self->_set_attributes($_, $attributes);
2036 $_ = $self->escapeHTML($_,1);
2037 push(@elements,$XHTML ? qq(<input type="checkbox" name="$name" value="$_"$checked$other$attribs />${label}${break})
2038 : qq/<input type="checkbox" name="$name" value="$_"$checked$other$attribs>${label}${break}/);
2040 $self->register_parameter($name);
2041 return wantarray ? @elements : join(' ',@elements)
2042 unless defined($columns) || defined($rows);
2043 $rows = 1 if $rows && $rows < 1;
2044 $cols = 1 if $cols && $cols < 1;
2045 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2049 # Escape HTML -- used internally
2050 'escapeHTML' => <<'END_OF_FUNC',
2052 # hack to work around earlier hacks
2053 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
2054 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
2055 return undef unless defined($toencode);
2056 return $toencode if ref($self) && !$self->{'escape'};
2057 $toencode =~ s{&}{&}gso;
2058 $toencode =~ s{<}{<}gso;
2059 $toencode =~ s{>}{>}gso;
2060 $toencode =~ s{"}{"}gso;
2061 my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
2062 uc $self->{'.charset'} eq 'WINDOWS-1252';
2063 if ($latin) { # bug in some browsers
2064 $toencode =~ s{'}{'}gso;
2065 $toencode =~ s{\x8b}{‹}gso;
2066 $toencode =~ s{\x9b}{›}gso;
2067 if (defined $newlinestoo && $newlinestoo) {
2068 $toencode =~ s{\012}{ }gso;
2069 $toencode =~ s{\015}{ }gso;
2076 # unescape HTML -- used internally
2077 'unescapeHTML' => <<'END_OF_FUNC',
2079 my ($self,$string) = CGI::self_or_default(@_);
2080 return undef unless defined($string);
2081 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
2083 # thanks to Randal Schwartz for the correct solution to this one
2084 $string=~ s[&(.*?);]{
2090 /^#(\d+)$/ && $latin ? chr($1) :
2091 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
2098 # Internal procedure - don't use
2099 '_tableize' => <<'END_OF_FUNC',
2101 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
2102 $rowheaders = [] unless defined $rowheaders;
2103 $colheaders = [] unless defined $colheaders;
2106 if (defined($columns)) {
2107 $rows = int(0.99 + @elements/$columns) unless defined($rows);
2109 if (defined($rows)) {
2110 $columns = int(0.99 + @elements/$rows) unless defined($columns);
2113 # rearrange into a pretty table
2114 $result = "<table>";
2116 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
2117 $result .= "<tr>" if @{$colheaders};
2118 foreach (@{$colheaders}) {
2119 $result .= "<th>$_</th>";
2121 for ($row=0;$row<$rows;$row++) {
2123 $result .= "<th>$rowheaders->[$row]</th>" if @$rowheaders;
2124 for ($column=0;$column<$columns;$column++) {
2125 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
2126 if defined($elements[$column*$rows + $row]);
2130 $result .= "</table>";
2136 #### Method: radio_group
2137 # Create a list of logically-linked radio buttons.
2139 # $name -> Common name for all the buttons.
2140 # $values -> A pointer to a regular array containing the
2141 # values for each button in the group.
2142 # $default -> (optional) Value of the button to turn on by default. Pass '-'
2143 # to turn _nothing_ on.
2144 # $linebreak -> (optional) Set to true to place linebreaks
2145 # between the buttons.
2146 # $labels -> (optional)
2147 # A pointer to an associative array of labels to print next to each checkbox
2148 # in the form $label{'value'}="Long explanatory label".
2149 # Otherwise the provided values are used as the labels.
2151 # An ARRAY containing a series of <input type="radio"> fields
2153 'radio_group' => <<'END_OF_FUNC',
2155 my($self,@p) = self_or_default(@_);
2157 my($name,$values,$default,$linebreak,$labels,$attributes,
2158 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
2159 rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,ATTRIBUTES,
2160 ROWS,[COLUMNS,COLS],
2161 ROWHEADERS,COLHEADERS,
2162 [OVERRIDE,FORCE],NOLABELS],@p);
2163 my($result,$checked);
2165 if (!$override && defined($self->param($name))) {
2166 $checked = $self->param($name);
2168 $checked = $default;
2170 my(@elements,@values);
2171 @values = $self->_set_values_and_labels($values,\$labels,$name);
2173 # If no check array is specified, check the first by default
2174 $checked = $values[0] unless defined($checked) && $checked ne '';
2175 $name=$self->escapeHTML($name);
2177 my($other) = @other ? " @other" : '';
2179 my($checkit) = $checked eq $_ ? qq/ checked="checked"/ : '';
2182 $break = $XHTML ? "<br />" : "<br>";
2188 unless (defined($nolabels) && $nolabels) {
2190 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2191 $label = $self->escapeHTML($label,1);
2193 my $attribs = $self->_set_attributes($_, $attributes);
2194 $_=$self->escapeHTML($_);
2195 push(@elements,$XHTML ? qq(<input type="radio" name="$name" value="$_"$checkit$other$attribs />${label}${break})
2196 : qq/<input type="radio" name="$name" value="$_"$checkit$other$attribs>${label}${break}/);
2198 $self->register_parameter($name);
2199 return wantarray ? @elements : join(' ',@elements)
2200 unless defined($columns) || defined($rows);
2201 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2206 #### Method: popup_menu
2207 # Create a popup menu.
2209 # $name -> Name for all the menu
2210 # $values -> A pointer to a regular array containing the
2211 # text of each menu item.
2212 # $default -> (optional) Default item to display
2213 # $labels -> (optional)
2214 # A pointer to an associative array of labels to print next to each checkbox
2215 # in the form $label{'value'}="Long explanatory label".
2216 # Otherwise the provided values are used as the labels.
2218 # A string containing the definition of a popup menu.
2220 'popup_menu' => <<'END_OF_FUNC',
2222 my($self,@p) = self_or_default(@_);
2224 my($name,$values,$default,$labels,$attributes,$override,@other) =
2225 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,
2226 ATTRIBUTES,[OVERRIDE,FORCE]],@p);
2227 my($result,$selected);
2229 if (!$override && defined($self->param($name))) {
2230 $selected = $self->param($name);
2232 $selected = $default;
2234 $name=$self->escapeHTML($name);
2235 my($other) = @other ? " @other" : '';
2238 @values = $self->_set_values_and_labels($values,\$labels,$name);
2240 $result = qq/<select name="$name"$other>\n/;
2243 foreach (split(/\n/)) {
2244 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2245 s/(value="$selected")/$selectit $1/ if defined $selected;
2250 my $attribs = $self->_set_attributes($_, $attributes);
2251 my($selectit) = defined($selected) ? $self->_selected($selected eq $_) : '';
2253 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2254 my($value) = $self->escapeHTML($_);
2255 $label=$self->escapeHTML($label,1);
2256 $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
2260 $result .= "</select>";
2266 #### Method: optgroup
2267 # Create a optgroup.
2269 # $name -> Label for the group
2270 # $values -> A pointer to a regular array containing the
2271 # values for each option line in the group.
2272 # $labels -> (optional)
2273 # A pointer to an associative array of labels to print next to each item
2274 # in the form $label{'value'}="Long explanatory label".
2275 # Otherwise the provided values are used as the labels.
2276 # $labeled -> (optional)
2277 # A true value indicates the value should be used as the label attribute
2278 # in the option elements.
2279 # The label attribute specifies the option label presented to the user.
2280 # This defaults to the content of the <option> element, but the label
2281 # attribute allows authors to more easily use optgroup without sacrificing
2282 # compatibility with browsers that do not support option groups.
2283 # $novals -> (optional)
2284 # A true value indicates to suppress the val attribute in the option elements
2286 # A string containing the definition of an option group.
2288 'optgroup' => <<'END_OF_FUNC',
2290 my($self,@p) = self_or_default(@_);
2291 my($name,$values,$attributes,$labeled,$noval,$labels,@other)
2292 = rearrange([NAME,[VALUES,VALUE],ATTRIBUTES,LABELED,NOVALS,LABELS],@p);
2294 my($result,@values);
2295 @values = $self->_set_values_and_labels($values,\$labels,$name,$labeled,$novals);
2296 my($other) = @other ? " @other" : '';
2298 $name=$self->escapeHTML($name);
2299 $result = qq/<optgroup label="$name"$other>\n/;
2302 foreach (split(/\n/)) {
2303 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2304 s/(value="$selected")/$selectit $1/ if defined $selected;
2309 my $attribs = $self->_set_attributes($_, $attributes);
2311 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2312 $label=$self->escapeHTML($label);
2313 my($value)=$self->escapeHTML($_,1);
2314 $result .= $labeled ? $novals ? "<option$attribs label=\"$value\">$label</option>\n"
2315 : "<option$attribs label=\"$value\" value=\"$value\">$label</option>\n"
2316 : $novals ? "<option$attribs>$label</option>\n"
2317 : "<option$attribs value=\"$value\">$label</option>\n";
2320 $result .= "</optgroup>";
2326 #### Method: scrolling_list
2327 # Create a scrolling list.
2329 # $name -> name for the list
2330 # $values -> A pointer to a regular array containing the
2331 # values for each option line in the list.
2332 # $defaults -> (optional)
2333 # 1. If a pointer to a regular array of options,
2334 # then this will be used to decide which
2335 # lines to turn on by default.
2336 # 2. Otherwise holds the value of the single line to turn on.
2337 # $size -> (optional) Size of the list.
2338 # $multiple -> (optional) If set, allow multiple selections.
2339 # $labels -> (optional)
2340 # A pointer to an associative array of labels to print next to each checkbox
2341 # in the form $label{'value'}="Long explanatory label".
2342 # Otherwise the provided values are used as the labels.
2344 # A string containing the definition of a scrolling list.
2346 'scrolling_list' => <<'END_OF_FUNC',
2347 sub scrolling_list {
2348 my($self,@p) = self_or_default(@_);
2349 my($name,$values,$defaults,$size,$multiple,$labels,$attributes,$override,@other)
2350 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2351 SIZE,MULTIPLE,LABELS,ATTRIBUTES,[OVERRIDE,FORCE]],@p);
2353 my($result,@values);
2354 @values = $self->_set_values_and_labels($values,\$labels,$name);
2356 $size = $size || scalar(@values);
2358 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2359 my($is_multiple) = $multiple ? qq/ multiple="multiple"/ : '';
2360 my($has_size) = $size ? qq/ size="$size"/: '';
2361 my($other) = @other ? " @other" : '';
2363 $name=$self->escapeHTML($name);
2364 $result = qq/<select name="$name"$has_size$is_multiple$other>\n/;
2366 my($selectit) = $self->_selected($selected{$_});
2368 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2369 $label=$self->escapeHTML($label);
2370 my($value)=$self->escapeHTML($_,1);
2371 my $attribs = $self->_set_attributes($_, $attributes);
2372 $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
2374 $result .= "</select>";
2375 $self->register_parameter($name);
2383 # $name -> Name of the hidden field
2384 # @default -> (optional) Initial values of field (may be an array)
2386 # $default->[initial values of field]
2388 # A string containing a <input type="hidden" name="name" value="value">
2390 'hidden' => <<'END_OF_FUNC',
2392 my($self,@p) = self_or_default(@_);
2394 # this is the one place where we departed from our standard
2395 # calling scheme, so we have to special-case (darn)
2397 my($name,$default,$override,@other) =
2398 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2400 my $do_override = 0;
2401 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2402 @value = ref($default) ? @{$default} : $default;
2403 $do_override = $override;
2405 foreach ($default,$override,@other) {
2406 push(@value,$_) if defined($_);
2410 # use previous values if override is not set
2411 my @prev = $self->param($name);
2412 @value = @prev if !$do_override && @prev;
2414 $name=$self->escapeHTML($name);
2416 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2417 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" />)
2418 : qq(<input type="hidden" name="$name" value="$_">);
2420 return wantarray ? @result : join('',@result);
2425 #### Method: image_button
2427 # $name -> Name of the button
2428 # $src -> URL of the image source
2429 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2431 # A string containing a <input type="image" name="name" src="url" align="alignment">
2433 'image_button' => <<'END_OF_FUNC',
2435 my($self,@p) = self_or_default(@_);
2437 my($name,$src,$alignment,@other) =
2438 rearrange([NAME,SRC,ALIGN],@p);
2440 my($align) = $alignment ? " align=\U\"$alignment\"" : '';
2441 my($other) = @other ? " @other" : '';
2442 $name=$self->escapeHTML($name);
2443 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2444 : qq/<input type="image" name="$name" src="$src"$align$other>/;
2449 #### Method: self_url
2450 # Returns a URL containing the current script and all its
2451 # param/value pairs arranged as a query. You can use this
2452 # to create a link that, when selected, will reinvoke the
2453 # script with all its state information preserved.
2455 'self_url' => <<'END_OF_FUNC',
2457 my($self,@p) = self_or_default(@_);
2458 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2463 # This is provided as a synonym to self_url() for people unfortunate
2464 # enough to have incorporated it into their programs already!
2465 'state' => <<'END_OF_FUNC',
2473 # Like self_url, but doesn't return the query string part of
2476 'url' => <<'END_OF_FUNC',
2478 my($self,@p) = self_or_default(@_);
2479 my ($relative,$absolute,$full,$path_info,$query,$base) =
2480 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE'],@p);
2482 $full++ if $base || !($relative || $absolute);
2484 my $path = $self->path_info;
2485 my $script_name = $self->script_name;
2487 # for compatibility with Apache's MultiViews
2488 if (exists($ENV{REQUEST_URI})) {
2490 $script_name = unescape($ENV{REQUEST_URI});
2491 $script_name =~ s/\?.+$//; # strip query string
2493 if (exists($ENV{PATH_INFO})) {
2494 my $encoded_path = quotemeta($ENV{PATH_INFO});
2495 $script_name =~ s/$encoded_path$//i;
2500 my $protocol = $self->protocol();
2501 $url = "$protocol://";
2502 my $vh = http('host');
2506 $url .= server_name();
2507 my $port = $self->server_port;
2509 unless (lc($protocol) eq 'http' && $port == 80)
2510 || (lc($protocol) eq 'https' && $port == 443);
2512 return $url if $base;
2513 $url .= $script_name;
2514 } elsif ($relative) {
2515 ($url) = $script_name =~ m!([^/]+)$!;
2516 } elsif ($absolute) {
2517 $url = $script_name;
2520 $url .= $path if $path_info and defined $path;
2521 $url .= "?" . $self->query_string if $query and $self->query_string;
2522 $url = '' unless defined $url;
2523 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/sprintf("%%%02X",ord($1))/eg;
2530 # Set or read a cookie from the specified name.
2531 # Cookie can then be passed to header().
2532 # Usual rules apply to the stickiness of -value.
2534 # -name -> name for this cookie (optional)
2535 # -value -> value of this cookie (scalar, array or hash)
2536 # -path -> paths for which this cookie is valid (optional)
2537 # -domain -> internet domain in which this cookie is valid (optional)
2538 # -secure -> if true, cookie only passed through secure channel (optional)
2539 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2541 'cookie' => <<'END_OF_FUNC',
2543 my($self,@p) = self_or_default(@_);
2544 my($name,$value,$path,$domain,$secure,$expires) =
2545 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2547 require CGI::Cookie;
2549 # if no value is supplied, then we retrieve the
2550 # value of the cookie, if any. For efficiency, we cache the parsed
2551 # cookies in our state variables.
2552 unless ( defined($value) ) {
2553 $self->{'.cookies'} = CGI::Cookie->fetch
2554 unless $self->{'.cookies'};
2556 # If no name is supplied, then retrieve the names of all our cookies.
2557 return () unless $self->{'.cookies'};
2558 return keys %{$self->{'.cookies'}} unless $name;
2559 return () unless $self->{'.cookies'}->{$name};
2560 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2563 # If we get here, we're creating a new cookie
2564 return undef unless defined($name) && $name ne ''; # this is an error
2567 push(@param,'-name'=>$name);
2568 push(@param,'-value'=>$value);
2569 push(@param,'-domain'=>$domain) if $domain;
2570 push(@param,'-path'=>$path) if $path;
2571 push(@param,'-expires'=>$expires) if $expires;
2572 push(@param,'-secure'=>$secure) if $secure;
2574 return new CGI::Cookie(@param);
2578 'parse_keywordlist' => <<'END_OF_FUNC',
2579 sub parse_keywordlist {
2580 my($self,$tosplit) = @_;
2581 $tosplit = unescape($tosplit); # unescape the keywords
2582 $tosplit=~tr/+/ /; # pluses to spaces
2583 my(@keywords) = split(/\s+/,$tosplit);
2588 'param_fetch' => <<'END_OF_FUNC',
2590 my($self,@p) = self_or_default(@_);
2591 my($name) = rearrange([NAME],@p);
2592 unless (exists($self->{$name})) {
2593 $self->add_parameter($name);
2594 $self->{$name} = [];
2597 return $self->{$name};
2601 ###############################################
2602 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2603 ###############################################
2605 #### Method: path_info
2606 # Return the extra virtual path information provided
2607 # after the URL (if any)
2609 'path_info' => <<'END_OF_FUNC',
2611 my ($self,$info) = self_or_default(@_);
2612 if (defined($info)) {
2613 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2614 $self->{'.path_info'} = $info;
2615 } elsif (! defined($self->{'.path_info'}) ) {
2616 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2617 $ENV{'PATH_INFO'} : '';
2619 # hack to fix broken path info in IIS
2620 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2623 return $self->{'.path_info'};
2628 #### Method: request_method
2629 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2631 'request_method' => <<'END_OF_FUNC',
2632 sub request_method {
2633 return $ENV{'REQUEST_METHOD'};
2637 #### Method: content_type
2638 # Returns the content_type string
2640 'content_type' => <<'END_OF_FUNC',
2642 return $ENV{'CONTENT_TYPE'};
2646 #### Method: path_translated
2647 # Return the physical path information provided
2648 # by the URL (if any)
2650 'path_translated' => <<'END_OF_FUNC',
2651 sub path_translated {
2652 return $ENV{'PATH_TRANSLATED'};
2657 #### Method: query_string
2658 # Synthesize a query string from our current
2661 'query_string' => <<'END_OF_FUNC',
2663 my($self) = self_or_default(@_);
2664 my($param,$value,@pairs);
2665 foreach $param ($self->param) {
2666 my($eparam) = escape($param);
2667 foreach $value ($self->param($param)) {
2668 $value = escape($value);
2669 next unless defined $value;
2670 push(@pairs,"$eparam=$value");
2673 foreach (keys %{$self->{'.fieldnames'}}) {
2674 push(@pairs,".cgifields=".escape("$_"));
2676 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2682 # Without parameters, returns an array of the
2683 # MIME types the browser accepts.
2684 # With a single parameter equal to a MIME
2685 # type, will return undef if the browser won't
2686 # accept it, 1 if the browser accepts it but
2687 # doesn't give a preference, or a floating point
2688 # value between 0.0 and 1.0 if the browser
2689 # declares a quantitative score for it.
2690 # This handles MIME type globs correctly.
2692 'Accept' => <<'END_OF_FUNC',
2694 my($self,$search) = self_or_CGI(@_);
2695 my(%prefs,$type,$pref,$pat);
2697 my(@accept) = split(',',$self->http('accept'));
2700 ($pref) = /q=(\d\.\d+|\d+)/;
2701 ($type) = m#(\S+/[^;]+)#;
2703 $prefs{$type}=$pref || 1;
2706 return keys %prefs unless $search;
2708 # if a search type is provided, we may need to
2709 # perform a pattern matching operation.
2710 # The MIME types use a glob mechanism, which
2711 # is easily translated into a perl pattern match
2713 # First return the preference for directly supported
2715 return $prefs{$search} if $prefs{$search};
2717 # Didn't get it, so try pattern matching.
2718 foreach (keys %prefs) {
2719 next unless /\*/; # not a pattern match
2720 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2721 $pat =~ s/\*/.*/g; # turn it into a pattern
2722 return $prefs{$_} if $search=~/$pat/;
2728 #### Method: user_agent
2729 # If called with no parameters, returns the user agent.
2730 # If called with one parameter, does a pattern match (case
2731 # insensitive) on the user agent.
2733 'user_agent' => <<'END_OF_FUNC',
2735 my($self,$match)=self_or_CGI(@_);
2736 return $self->http('user_agent') unless $match;
2737 return $self->http('user_agent') =~ /$match/i;
2742 #### Method: raw_cookie
2743 # Returns the magic cookies for the session.
2744 # The cookies are not parsed or altered in any way, i.e.
2745 # cookies are returned exactly as given in the HTTP
2746 # headers. If a cookie name is given, only that cookie's
2747 # value is returned, otherwise the entire raw cookie
2750 'raw_cookie' => <<'END_OF_FUNC',
2752 my($self,$key) = self_or_CGI(@_);
2754 require CGI::Cookie;
2756 if (defined($key)) {
2757 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2758 unless $self->{'.raw_cookies'};
2760 return () unless $self->{'.raw_cookies'};
2761 return () unless $self->{'.raw_cookies'}->{$key};
2762 return $self->{'.raw_cookies'}->{$key};
2764 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2768 #### Method: virtual_host
2769 # Return the name of the virtual_host, which
2770 # is not always the same as the server
2772 'virtual_host' => <<'END_OF_FUNC',
2774 my $vh = http('host') || server_name();
2775 $vh =~ s/:\d+$//; # get rid of port number
2780 #### Method: remote_host
2781 # Return the name of the remote host, or its IP
2782 # address if unavailable. If this variable isn't
2783 # defined, it returns "localhost" for debugging
2786 'remote_host' => <<'END_OF_FUNC',
2788 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2794 #### Method: remote_addr
2795 # Return the IP addr of the remote host.
2797 'remote_addr' => <<'END_OF_FUNC',
2799 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2804 #### Method: script_name
2805 # Return the partial URL to this script for
2806 # self-referencing scripts. Also see
2807 # self_url(), which returns a URL with all state information
2810 'script_name' => <<'END_OF_FUNC',
2812 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2813 # These are for debugging
2814 return "/$0" unless $0=~/^\//;
2820 #### Method: referer
2821 # Return the HTTP_REFERER: useful for generating
2824 'referer' => <<'END_OF_FUNC',
2826 my($self) = self_or_CGI(@_);
2827 return $self->http('referer');
2832 #### Method: server_name
2833 # Return the name of the server
2835 'server_name' => <<'END_OF_FUNC',
2837 return $ENV{'SERVER_NAME'} || 'localhost';
2841 #### Method: server_software
2842 # Return the name of the server software
2844 'server_software' => <<'END_OF_FUNC',
2845 sub server_software {
2846 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2850 #### Method: server_port
2851 # Return the tcp/ip port the server is running on
2853 'server_port' => <<'END_OF_FUNC',
2855 return $ENV{'SERVER_PORT'} || 80; # for debugging
2859 #### Method: server_protocol
2860 # Return the protocol (usually HTTP/1.0)
2862 'server_protocol' => <<'END_OF_FUNC',
2863 sub server_protocol {
2864 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2869 # Return the value of an HTTP variable, or
2870 # the list of variables if none provided
2872 'http' => <<'END_OF_FUNC',
2874 my ($self,$parameter) = self_or_CGI(@_);
2875 return $ENV{$parameter} if $parameter=~/^HTTP/;
2876 $parameter =~ tr/-/_/;
2877 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2879 foreach (keys %ENV) {
2880 push(@p,$_) if /^HTTP/;
2887 # Return the value of HTTPS
2889 'https' => <<'END_OF_FUNC',
2892 my ($self,$parameter) = self_or_CGI(@_);
2893 return $ENV{HTTPS} unless $parameter;
2894 return $ENV{$parameter} if $parameter=~/^HTTPS/;
2895 $parameter =~ tr/-/_/;
2896 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2898 foreach (keys %ENV) {
2899 push(@p,$_) if /^HTTPS/;
2905 #### Method: protocol
2906 # Return the protocol (http or https currently)
2908 'protocol' => <<'END_OF_FUNC',
2912 return 'https' if uc($self->https()) eq 'ON';
2913 return 'https' if $self->server_port == 443;
2914 my $prot = $self->server_protocol;
2915 my($protocol,$version) = split('/',$prot);
2916 return "\L$protocol\E";
2920 #### Method: remote_ident
2921 # Return the identity of the remote user
2922 # (but only if his host is running identd)
2924 'remote_ident' => <<'END_OF_FUNC',
2926 return $ENV{'REMOTE_IDENT'};
2931 #### Method: auth_type
2932 # Return the type of use verification/authorization in use, if any.
2934 'auth_type' => <<'END_OF_FUNC',
2936 return $ENV{'AUTH_TYPE'};
2941 #### Method: remote_user
2942 # Return the authorization name used for user
2945 'remote_user' => <<'END_OF_FUNC',
2947 return $ENV{'REMOTE_USER'};
2952 #### Method: user_name
2953 # Try to return the remote user's name by hook or by
2956 'user_name' => <<'END_OF_FUNC',
2958 my ($self) = self_or_CGI(@_);
2959 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
2963 #### Method: nosticky
2964 # Set or return the NOSTICKY global flag
2966 'nosticky' => <<'END_OF_FUNC',
2968 my ($self,$param) = self_or_CGI(@_);
2969 $CGI::NOSTICKY = $param if defined($param);
2970 return $CGI::NOSTICKY;
2975 # Set or return the NPH global flag
2977 'nph' => <<'END_OF_FUNC',
2979 my ($self,$param) = self_or_CGI(@_);
2980 $CGI::NPH = $param if defined($param);
2985 #### Method: private_tempfiles
2986 # Set or return the private_tempfiles global flag
2988 'private_tempfiles' => <<'END_OF_FUNC',
2989 sub private_tempfiles {
2990 my ($self,$param) = self_or_CGI(@_);
2991 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
2992 return $CGI::PRIVATE_TEMPFILES;
2995 #### Method: close_upload_files
2996 # Set or return the close_upload_files global flag
2998 'close_upload_files' => <<'END_OF_FUNC',
2999 sub close_upload_files {
3000 my ($self,$param) = self_or_CGI(@_);
3001 $CGI::CLOSE_UPLOAD_FILES = $param if defined($param);
3002 return $CGI::CLOSE_UPLOAD_FILES;
3007 #### Method: default_dtd
3008 # Set or return the default_dtd global
3010 'default_dtd' => <<'END_OF_FUNC',
3012 my ($self,$param,$param2) = self_or_CGI(@_);
3013 if (defined $param2 && defined $param) {
3014 $CGI::DEFAULT_DTD = [ $param, $param2 ];
3015 } elsif (defined $param) {
3016 $CGI::DEFAULT_DTD = $param;
3018 return $CGI::DEFAULT_DTD;
3022 # -------------- really private subroutines -----------------
3023 'previous_or_default' => <<'END_OF_FUNC',
3024 sub previous_or_default {
3025 my($self,$name,$defaults,$override) = @_;
3028 if (!$override && ($self->{'.fieldnames'}->{$name} ||
3029 defined($self->param($name)) ) ) {
3030 grep($selected{$_}++,$self->param($name));
3031 } elsif (defined($defaults) && ref($defaults) &&
3032 (ref($defaults) eq 'ARRAY')) {
3033 grep($selected{$_}++,@{$defaults});
3035 $selected{$defaults}++ if defined($defaults);
3042 'register_parameter' => <<'END_OF_FUNC',
3043 sub register_parameter {
3044 my($self,$param) = @_;
3045 $self->{'.parametersToAdd'}->{$param}++;
3049 'get_fields' => <<'END_OF_FUNC',
3052 return $self->CGI::hidden('-name'=>'.cgifields',
3053 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
3058 'read_from_cmdline' => <<'END_OF_FUNC',
3059 sub read_from_cmdline {
3062 if ($DEBUG && @ARGV) {
3064 } elsif ($DEBUG > 1) {
3065 require "shellwords.pl";
3066 print STDERR "(offline mode: enter name=value pairs on standard input)\n";
3067 chomp(@lines = <STDIN>); # remove newlines
3068 $input = join(" ",@lines);
3069 @words = &shellwords($input);
3076 if ("@words"=~/=/) {
3077 $query_string = join('&',@words);
3079 $query_string = join('+',@words);
3081 return $query_string;
3086 # subroutine: read_multipart
3088 # Read multipart data and store it into our parameters.
3089 # An interesting feature is that if any of the parts is a file, we
3090 # create a temporary file and open up a filehandle on it so that the
3091 # caller can read from it if necessary.
3093 'read_multipart' => <<'END_OF_FUNC',
3094 sub read_multipart {
3095 my($self,$boundary,$length,$filehandle) = @_;
3096 my($buffer) = $self->new_MultipartBuffer($boundary,$length,$filehandle);
3097 return unless $buffer;
3100 while (!$buffer->eof) {
3101 %header = $buffer->readHeader;
3104 $self->cgi_error("400 Bad request (malformed multipart POST)");
3108 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
3111 # Bug: Netscape doesn't escape quotation marks in file names!!!
3112 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\"]*)"?/;
3113 # Test for Opera's multiple upload feature
3114 my($multipart) = ( defined( $header{'Content-Type'} ) &&
3115 $header{'Content-Type'} =~ /multipart\/mixed/ ) ?
3118 # add this parameter to our list
3119 $self->add_parameter($param);
3121 # If no filename specified, then just read the data and assign it
3122 # to our parameter list.
3123 if ( ( !defined($filename) || $filename eq '' ) && !$multipart ) {
3124 my($value) = $buffer->readBody;
3126 push(@{$self->{$param}},$value);
3130 my ($tmpfile,$tmp,$filehandle);
3132 # If we get here, then we are dealing with a potentially large
3133 # uploaded form. Save the data to a temporary file, then open
3134 # the file for reading.
3136 # skip the file if uploads disabled
3137 if ($DISABLE_UPLOADS) {
3138 while (defined($data = $buffer->read)) { }
3142 # set the filename to some recognizable value
3143 if ( ( !defined($filename) || $filename eq '' ) && $multipart ) {
3144 $filename = "multipart/mixed";
3147 # choose a relatively unpredictable tmpfile sequence number
3148 my $seqno = unpack("%16C*",join('',localtime,values %ENV));
3149 for (my $cnt=10;$cnt>0;$cnt--) {
3150 next unless $tmpfile = new CGITempFile($seqno);
3151 $tmp = $tmpfile->as_string;
3152 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
3153 $seqno += int rand(100);
3155 die "CGI open of tmpfile: $!\n" unless defined $filehandle;
3156 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3158 # if this is an multipart/mixed attachment, save the header
3159 # together with the body for lateron parsing with an external
3160 # MIME parser module
3162 foreach ( keys %header ) {
3163 print $filehandle "$_: $header{$_}${CRLF}";
3165 print $filehandle "${CRLF}";
3170 while (defined($data = $buffer->read)) {
3171 print $filehandle $data;
3174 # back up to beginning of file
3175 seek($filehandle,0,0);
3177 ## Close the filehandle if requested this allows a multipart MIME
3178 ## upload to contain many files, and we won't die due to too many
3179 ## open file handles. The user can access the files using the hash
3181 close $filehandle if $CLOSE_UPLOAD_FILES;
3182 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3184 # Save some information about the uploaded file where we can get
3186 $self->{'.tmpfiles'}->{fileno($filehandle)}= {
3190 push(@{$self->{$param}},$filehandle);
3196 'upload' =><<'END_OF_FUNC',
3198 my($self,$param_name) = self_or_default(@_);
3199 my @param = grep(ref && fileno($_), $self->param($param_name));
3200 return unless @param;
3201 return wantarray ? @param : $param[0];
3205 'tmpFileName' => <<'END_OF_FUNC',
3207 my($self,$filename) = self_or_default(@_);
3208 return $self->{'.tmpfiles'}->{fileno($filename)}->{name} ?
3209 $self->{'.tmpfiles'}->{fileno($filename)}->{name}->as_string
3214 'uploadInfo' => <<'END_OF_FUNC',
3216 my($self,$filename) = self_or_default(@_);
3217 return $self->{'.tmpfiles'}->{fileno($filename)}->{info};
3221 # internal routine, don't use
3222 '_set_values_and_labels' => <<'END_OF_FUNC',
3223 sub _set_values_and_labels {
3226 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
3227 return $self->param($n) if !defined($v);
3228 return $v if !ref($v);
3229 return ref($v) eq 'HASH' ? keys %$v : @$v;
3233 # internal routine, don't use
3234 '_set_attributes' => <<'END_OF_FUNC',
3235 sub _set_attributes {
3237 my($element, $attributes) = @_;
3238 return '' unless defined($attributes->{$element});
3240 foreach my $attrib (keys %{$attributes->{$element}}) {
3242 $attribs .= "@{[lc($attrib)]}=\"$attributes->{$element}{$attrib}\" ";
3249 '_compile_all' => <<'END_OF_FUNC',
3252 next if defined(&$_);
3253 $AUTOLOAD = "CGI::$_";
3263 #########################################################
3264 # Globals and stubs for other packages that we use.
3265 #########################################################
3267 ################### Fh -- lightweight filehandle ###############
3276 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3278 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3279 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3281 'asString' => <<'END_OF_FUNC',
3284 # get rid of package name
3285 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
3286 $i =~ s/%(..)/ chr(hex($1)) /eg;
3287 return $i.$CGI::TAINTED;
3289 # This was an extremely clever patch that allowed "use strict refs".
3290 # Unfortunately it relied on another bug that caused leaky file descriptors.
3291 # The underlying bug has been fixed, so this no longer works. However
3292 # "strict refs" still works for some reason.
3294 # return ${*{$self}{SCALAR}};
3299 'compare' => <<'END_OF_FUNC',
3303 return "$self" cmp $value;
3307 'new' => <<'END_OF_FUNC',
3309 my($pack,$name,$file,$delete) = @_;
3310 _setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
3311 require Fcntl unless defined &Fcntl::O_RDWR;
3312 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3313 my $fv = ++$FH . $safename;
3314 my $ref = \*{"Fh::$fv"};
3315 $file =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3317 sysopen($ref,$safe,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3318 unlink($safe) if $delete;
3319 CORE::delete $Fh::{$fv};
3320 return bless $ref,$pack;
3324 'DESTROY' => <<'END_OF_FUNC',
3334 ######################## MultipartBuffer ####################
3335 package MultipartBuffer;
3337 # how many bytes to read at a time. We use
3338 # a 4K buffer by default.
3339 $INITIAL_FILLUNIT = 1024 * 4;
3340 $TIMEOUT = 240*60; # 4 hour timeout for big files
3341 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3344 #reuse the autoload function
3345 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3347 # avoid autoloader warnings
3350 ###############################################################################
3351 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3352 ###############################################################################
3353 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3354 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3357 'new' => <<'END_OF_FUNC',
3359 my($package,$interface,$boundary,$length,$filehandle) = @_;
3360 $FILLUNIT = $INITIAL_FILLUNIT;
3363 my($package) = caller;
3364 # force into caller's package if necessary
3365 $IN = $filehandle=~/[':]/ ? $filehandle : "$package\:\:$filehandle";
3367 $IN = "main::STDIN" unless $IN;
3369 $CGI::DefaultClass->binmode($IN) if $CGI::needs_binmode;
3371 # If the user types garbage into the file upload field,
3372 # then Netscape passes NOTHING to the server (not good).
3373 # We may hang on this read in that case. So we implement
3374 # a read timeout. If nothing is ready to read
3375 # by then, we return.
3377 # Netscape seems to be a little bit unreliable
3378 # about providing boundary strings.
3379 my $boundary_read = 0;
3382 # Under the MIME spec, the boundary consists of the
3383 # characters "--" PLUS the Boundary string
3385 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3386 # the two extra hyphens. We do a special case here on the user-agent!!!!
3387 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac|DreamPassport');
3389 } else { # otherwise we find it ourselves
3391 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3392 $boundary = <$IN>; # BUG: This won't work correctly under mod_perl
3393 $length -= length($boundary);
3394 chomp($boundary); # remove the CRLF
3395 $/ = $old; # restore old line separator
3399 my $self = {LENGTH=>$length,
3400 BOUNDARY=>$boundary,
3402 INTERFACE=>$interface,
3406 $FILLUNIT = length($boundary)
3407 if length($boundary) > $FILLUNIT;
3409 my $retval = bless $self,ref $package || $package;
3411 # Read the preamble and the topmost (boundary) line plus the CRLF.
3412 unless ($boundary_read) {
3413 while ($self->read(0)) { }
3415 die "Malformed multipart POST\n" if $self->eof;
3421 'readHeader' => <<'END_OF_FUNC',
3428 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
3431 $self->fillBuffer($FILLUNIT);
3432 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3433 $ok++ if $self->{BUFFER} eq '';
3434 $bad++ if !$ok && $self->{LENGTH} <= 0;
3435 # this was a bad idea
3436 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3437 } until $ok || $bad;
3440 my($header) = substr($self->{BUFFER},0,$end+2);
3441 substr($self->{BUFFER},0,$end+4) = '';
3444 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3445 # (Folding Long Header Fields), 3.4.3 (Comments)
3446 # and 3.4.5 (Quoted-Strings).
3448 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3449 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3451 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3452 my ($field_name,$field_value) = ($1,$2);
3453 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3454 $return{$field_name}=$field_value;
3460 # This reads and returns the body as a single scalar value.
3461 'readBody' => <<'END_OF_FUNC',
3466 while (defined($data = $self->read)) {
3467 $returnval .= $data;
3473 # This will read $bytes or until the boundary is hit, whichever happens
3474 # first. After the boundary is hit, we return undef. The next read will
3475 # skip over the boundary and begin reading again;
3476 'read' => <<'END_OF_FUNC',
3478 my($self,$bytes) = @_;
3480 # default number of bytes to read
3481 $bytes = $bytes || $FILLUNIT;
3483 # Fill up our internal buffer in such a way that the boundary
3484 # is never split between reads.
3485 $self->fillBuffer($bytes);
3487 # Find the boundary in the buffer (it may not be there).
3488 my $start = index($self->{BUFFER},$self->{BOUNDARY});
3489 # protect against malformed multipart POST operations
3490 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3492 # If the boundary begins the data, then skip past it
3496 # clear us out completely if we've hit the last boundary.
3497 if (index($self->{BUFFER},"$self->{BOUNDARY}--")==0) {
3503 # just remove the boundary.
3504 substr($self->{BUFFER},0,length($self->{BOUNDARY}))='';
3505 $self->{BUFFER} =~ s/^\012\015?//;
3510 if ($start > 0) { # read up to the boundary
3511 $bytesToReturn = $start-2 > $bytes ? $bytes : $start;
3512 } else { # read the requested number of bytes
3513 # leave enough bytes in the buffer to allow us to read
3514 # the boundary. Thanks to Kevin Hendrick for finding
3516 $bytesToReturn = $bytes - (length($self->{BOUNDARY})+1);
3519 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3520 substr($self->{BUFFER},0,$bytesToReturn)='';
3522 # If we hit the boundary, remove the CRLF from the end.
3523 return ($bytesToReturn==$start)
3524 ? substr($returnval,0,-2) : $returnval;
3529 # This fills up our internal buffer in such a way that the
3530 # boundary is never split between reads
3531 'fillBuffer' => <<'END_OF_FUNC',
3533 my($self,$bytes) = @_;
3534 return unless $self->{LENGTH};
3536 my($boundaryLength) = length($self->{BOUNDARY});
3537 my($bufferLength) = length($self->{BUFFER});
3538 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3539 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3541 # Try to read some data. We may hang here if the browser is screwed up.
3542 my $bytesRead = $self->{INTERFACE}->read_from_client($self->{IN},
3546 $self->{BUFFER} = '' unless defined $self->{BUFFER};
3548 # An apparent bug in the Apache server causes the read()
3549 # to return zero bytes repeatedly without blocking if the
3550 # remote user aborts during a file transfer. I don't know how
3551 # they manage this, but the workaround is to abort if we get
3552 # more than SPIN_LOOP_MAX consecutive zero reads.
3553 if ($bytesRead == 0) {
3554 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3555 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3557 $self->{ZERO_LOOP_COUNTER}=0;
3560 $self->{LENGTH} -= $bytesRead;
3565 # Return true when we've finished reading
3566 'eof' => <<'END_OF_FUNC'
3569 return 1 if (length($self->{BUFFER}) == 0)
3570 && ($self->{LENGTH} <= 0);
3578 ####################################################################################
3579 ################################## TEMPORARY FILES #################################
3580 ####################################################################################
3581 package CGITempFile;
3584 $MAC = $CGI::OS eq 'MACINTOSH';
3585 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3586 unless ($TMPDIRECTORY) {
3587 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3588 "C:${SL}temp","${SL}tmp","${SL}temp",
3589 "${vol}${SL}Temporary Items",
3590 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3591 "C:${SL}system${SL}temp");
3592 unshift(@TEMP,$ENV{'TMPDIR'}) if defined $ENV{'TMPDIR'};
3594 # this feature was supposed to provide per-user tmpfiles, but
3595 # it is problematic.
3596 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3597 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3598 # : can generate a 'getpwuid() not implemented' exception, even though
3599 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3600 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3601 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3604 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3608 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3611 # cute feature, but overload implementation broke it
3612 # %OVERLOAD = ('""'=>'as_string');
3613 *CGITempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3617 $$self =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3618 my $safe = $1; # untaint operation
3619 unlink $safe; # get rid of the file
3622 ###############################################################################
3623 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3624 ###############################################################################
3625 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3626 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3629 'new' => <<'END_OF_FUNC',
3631 my($package,$sequence) = @_;
3633 for (my $i = 0; $i < $MAXTRIES; $i++) {
3634 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3636 # check that it is a more-or-less valid filename
3637 return unless $filename =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$!;
3638 # this used to untaint, now it doesn't
3640 return bless \$filename;
3644 'as_string' => <<'END_OF_FUNC'
3656 # We get a whole bunch of warnings about "possibly uninitialized variables"
3657 # when running with the -w switch. Touch them all once to get rid of the
3658 # warnings. This is ugly and I hate it.
3663 $MultipartBuffer::SPIN_LOOP_MAX;
3664 $MultipartBuffer::CRLF;
3665 $MultipartBuffer::TIMEOUT;
3666 $MultipartBuffer::INITIAL_FILLUNIT;
3677 CGI - Simple Common Gateway Interface Class
3681 # CGI script that creates a fill-out form
3682 # and echoes back its values.
3684 use CGI qw/:standard/;
3686 start_html('A Simple Example'),
3687 h1('A Simple Example'),
3689 "What's your name? ",textfield('name'),p,
3690 "What's the combination?", p,
3691 checkbox_group(-name=>'words',
3692 -values=>['eenie','meenie','minie','moe'],
3693 -defaults=>['eenie','minie']), p,
3694 "What's your favorite color? ",
3695 popup_menu(-name=>'color',
3696 -values=>['red','green','blue','chartreuse']),p,
3702 print "Your name is",em(param('name')),p,
3703 "The keywords are: ",em(join(", ",param('words'))),p,
3704 "Your favorite color is ",em(param('color')),
3710 This perl library uses perl5 objects to make it easy to create Web
3711 fill-out forms and parse their contents. This package defines CGI
3712 objects, entities that contain the values of the current query string
3713 and other state variables. Using a CGI object's methods, you can
3714 examine keywords and parameters passed to your script, and create
3715 forms whose initial values are taken from the current query (thereby
3716 preserving state information). The module provides shortcut functions
3717 that produce boilerplate HTML, reducing typing and coding errors. It
3718 also provides functionality for some of the more advanced features of
3719 CGI scripting, including support for file uploads, cookies, cascading
3720 style sheets, server push, and frames.
3722 CGI.pm also provides a simple function-oriented programming style for
3723 those who don't need its object-oriented features.
3725 The current version of CGI.pm is available at
3727 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3728 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3732 =head2 PROGRAMMING STYLE
3734 There are two styles of programming with CGI.pm, an object-oriented
3735 style and a function-oriented style. In the object-oriented style you
3736 create one or more CGI objects and then use object methods to create
3737 the various elements of the page. Each CGI object starts out with the
3738 list of named parameters that were passed to your CGI script by the
3739 server. You can modify the objects, save them to a file or database
3740 and recreate them. Because each object corresponds to the "state" of
3741 the CGI script, and because each object's parameter list is
3742 independent of the others, this allows you to save the state of the
3743 script and restore it later.
3745 For example, using the object oriented style, here is how you create
3746 a simple "Hello World" HTML page:
3748 #!/usr/local/bin/perl -w
3749 use CGI; # load CGI routines
3750 $q = new CGI; # create new CGI object
3751 print $q->header, # create the HTTP header
3752 $q->start_html('hello world'), # start the HTML
3753 $q->h1('hello world'), # level 1 header
3754 $q->end_html; # end the HTML
3756 In the function-oriented style, there is one default CGI object that
3757 you rarely deal with directly. Instead you just call functions to
3758 retrieve CGI parameters, create HTML tags, manage cookies, and so
3759 on. This provides you with a cleaner programming interface, but
3760 limits you to using one CGI object at a time. The following example
3761 prints the same page, but uses the function-oriented interface.
3762 The main differences are that we now need to import a set of functions
3763 into our name space (usually the "standard" functions), and we don't
3764 need to create the CGI object.
3766 #!/usr/local/bin/perl
3767 use CGI qw/:standard/; # load standard CGI routines
3768 print header, # create the HTTP header
3769 start_html('hello world'), # start the HTML
3770 h1('hello world'), # level 1 header
3771 end_html; # end the HTML
3773 The examples in this document mainly use the object-oriented style.
3774 See HOW TO IMPORT FUNCTIONS for important information on
3775 function-oriented programming in CGI.pm
3777 =head2 CALLING CGI.PM ROUTINES
3779 Most CGI.pm routines accept several arguments, sometimes as many as 20
3780 optional ones! To simplify this interface, all routines use a named
3781 argument calling style that looks like this:
3783 print $q->header(-type=>'image/gif',-expires=>'+3d');
3785 Each argument name is preceded by a dash. Neither case nor order
3786 matters in the argument list. -type, -Type, and -TYPE are all
3787 acceptable. In fact, only the first argument needs to begin with a
3788 dash. If a dash is present in the first argument, CGI.pm assumes
3789 dashes for the subsequent ones.
3791 Several routines are commonly called with just one argument. In the
3792 case of these routines you can provide the single argument without an
3793 argument name. header() happens to be one of these routines. In this
3794 case, the single argument is the document type.
3796 print $q->header('text/html');
3798 Other such routines are documented below.
3800 Sometimes named arguments expect a scalar, sometimes a reference to an
3801 array, and sometimes a reference to a hash. Often, you can pass any
3802 type of argument and the routine will do whatever is most appropriate.
3803 For example, the param() routine is used to set a CGI parameter to a
3804 single or a multi-valued value. The two cases are shown below:
3806 $q->param(-name=>'veggie',-value=>'tomato');
3807 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
3809 A large number of routines in CGI.pm actually aren't specifically
3810 defined in the module, but are generated automatically as needed.
3811 These are the "HTML shortcuts," routines that generate HTML tags for
3812 use in dynamically-generated pages. HTML tags have both attributes
3813 (the attribute="value" pairs within the tag itself) and contents (the
3814 part between the opening and closing pairs.) To distinguish between
3815 attributes and contents, CGI.pm uses the convention of passing HTML
3816 attributes as a hash reference as the first argument, and the
3817 contents, if any, as any subsequent arguments. It works out like
3823 h1('some','contents'); <h1>some contents</h1>
3824 h1({-align=>left}); <h1 align="LEFT">
3825 h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
3827 HTML tags are described in more detail later.
3829 Many newcomers to CGI.pm are puzzled by the difference between the
3830 calling conventions for the HTML shortcuts, which require curly braces
3831 around the HTML tag attributes, and the calling conventions for other
3832 routines, which manage to generate attributes without the curly
3833 brackets. Don't be confused. As a convenience the curly braces are
3834 optional in all but the HTML shortcuts. If you like, you can use
3835 curly braces when calling any routine that takes named arguments. For
3838 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3840 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3841 names conflict with built-in Perl functions. The most frequent of
3842 these is the -values argument, used to create multi-valued menus,
3843 radio button clusters and the like. To get around this warning, you
3844 have several choices:
3850 Use another name for the argument, if one is available.
3851 For example, -value is an alias for -values.
3855 Change the capitalization, e.g. -Values
3859 Put quotes around the argument name, e.g. '-values'
3863 Many routines will do something useful with a named argument that it
3864 doesn't recognize. For example, you can produce non-standard HTTP
3865 header fields by providing them as named arguments:
3867 print $q->header(-type => 'text/html',
3868 -cost => 'Three smackers',
3869 -annoyance_level => 'high',
3870 -complaints_to => 'bit bucket');
3872 This will produce the following nonstandard HTTP header:
3875 Cost: Three smackers
3876 Annoyance-level: high
3877 Complaints-to: bit bucket
3878 Content-type: text/html
3880 Notice the way that underscores are translated automatically into
3881 hyphens. HTML-generating routines perform a different type of
3884 This feature allows you to keep up with the rapidly changing HTTP and
3887 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
3891 This will parse the input (from both POST and GET methods) and store
3892 it into a perl5 object called $query.
3894 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
3896 $query = new CGI(INPUTFILE);
3898 If you provide a file handle to the new() method, it will read
3899 parameters from the file (or STDIN, or whatever). The file can be in
3900 any of the forms describing below under debugging (i.e. a series of
3901 newline delimited TAG=VALUE pairs will work). Conveniently, this type
3902 of file is created by the save() method (see below). Multiple records
3903 can be saved and restored.
3905 Perl purists will be pleased to know that this syntax accepts
3906 references to file handles, or even references to filehandle globs,
3907 which is the "official" way to pass a filehandle:
3909 $query = new CGI(\*STDIN);
3911 You can also initialize the CGI object with a FileHandle or IO::File
3914 If you are using the function-oriented interface and want to
3915 initialize CGI state from a file handle, the way to do this is with
3916 B<restore_parameters()>. This will (re)initialize the
3917 default CGI object from the indicated file handle.
3919 open (IN,"test.in") || die;
3920 restore_parameters(IN);
3923 You can also initialize the query object from an associative array
3926 $query = new CGI( {'dinosaur'=>'barney',
3927 'song'=>'I love you',
3928 'friends'=>[qw/Jessica George Nancy/]}
3931 or from a properly formatted, URL-escaped query string:
3933 $query = new CGI('dinosaur=barney&color=purple');
3935 or from a previously existing CGI object (currently this clones the
3936 parameter list, but none of the other object-specific fields, such as
3939 $old_query = new CGI;
3940 $new_query = new CGI($old_query);
3942 To create an empty query, initialize it from an empty string or hash:
3944 $empty_query = new CGI("");
3948 $empty_query = new CGI({});
3950 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
3952 @keywords = $query->keywords
3954 If the script was invoked as the result of an <ISINDEX> search, the
3955 parsed keywords can be obtained as an array using the keywords() method.
3957 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
3959 @names = $query->param
3961 If the script was invoked with a parameter list
3962 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
3963 will return the parameter names as a list. If the script was invoked
3964 as an <ISINDEX> script and contains a string without ampersands
3965 (e.g. "value1+value2+value3") , there will be a single parameter named
3966 "keywords" containing the "+"-delimited keywords.
3968 NOTE: As of version 1.5, the array of parameter names returned will
3969 be in the same order as they were submitted by the browser.
3970 Usually this order is the same as the order in which the
3971 parameters are defined in the form (however, this isn't part
3972 of the spec, and so isn't guaranteed).
3974 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
3976 @values = $query->param('foo');
3980 $value = $query->param('foo');
3982 Pass the param() method a single argument to fetch the value of the
3983 named parameter. If the parameter is multivalued (e.g. from multiple
3984 selections in a scrolling list), you can ask to receive an array. Otherwise
3985 the method will return a single value.
3987 If a value is not given in the query string, as in the queries
3988 "name1=&name2=" or "name1&name2", it will be returned as an empty
3989 string. This feature is new in 2.63.
3992 If the parameter does not exist at all, then param() will return undef
3993 in a scalar context, and the empty list in a list context.
3996 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
3998 $query->param('foo','an','array','of','values');
4000 This sets the value for the named parameter 'foo' to an array of
4001 values. This is one way to change the value of a field AFTER
4002 the script has been invoked once before. (Another way is with
4003 the -override parameter accepted by all methods that generate
4006 param() also recognizes a named parameter style of calling described
4007 in more detail later:
4009 $query->param(-name=>'foo',-values=>['an','array','of','values']);
4013 $query->param(-name=>'foo',-value=>'the value');
4015 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
4017 $query->append(-name=>'foo',-values=>['yet','more','values']);
4019 This adds a value or list of values to the named parameter. The
4020 values are appended to the end of the parameter if it already exists.
4021 Otherwise the parameter is created. Note that this method only
4022 recognizes the named argument calling syntax.
4024 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
4026 $query->import_names('R');
4028 This creates a series of variables in the 'R' namespace. For example,
4029 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
4030 If no namespace is given, this method will assume 'Q'.
4031 WARNING: don't import anything into 'main'; this is a major security
4034 NOTE 1: Variable names are transformed as necessary into legal Perl
4035 variable names. All non-legal characters are transformed into
4036 underscores. If you need to keep the original names, you should use
4037 the param() method instead to access CGI variables by name.
4039 NOTE 2: In older versions, this method was called B<import()>. As of version 2.20,
4040 this name has been removed completely to avoid conflict with the built-in
4041 Perl module B<import> operator.
4043 =head2 DELETING A PARAMETER COMPLETELY:
4045 $query->delete('foo','bar','baz');
4047 This completely clears a list of parameters. It sometimes useful for
4048 resetting parameters that you don't want passed down between script
4051 If you are using the function call interface, use "Delete()" instead
4052 to avoid conflicts with Perl's built-in delete operator.
4054 =head2 DELETING ALL PARAMETERS:
4056 $query->delete_all();
4058 This clears the CGI object completely. It might be useful to ensure
4059 that all the defaults are taken when you create a fill-out form.
4061 Use Delete_all() instead if you are using the function call interface.
4063 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
4065 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
4066 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
4068 If you need access to the parameter list in a way that isn't covered
4069 by the methods above, you can obtain a direct reference to it by
4070 calling the B<param_fetch()> method with the name of the . This
4071 will return an array reference to the named parameters, which you then
4072 can manipulate in any way you like.
4074 You can also use a named argument style using the B<-name> argument.
4076 =head2 FETCHING THE PARAMETER LIST AS A HASH:
4079 print $params->{'address'};
4080 @foo = split("\0",$params->{'foo'});
4086 Many people want to fetch the entire parameter list as a hash in which
4087 the keys are the names of the CGI parameters, and the values are the
4088 parameters' values. The Vars() method does this. Called in a scalar
4089 context, it returns the parameter list as a tied hash reference.
4090 Changing a key changes the value of the parameter in the underlying
4091 CGI parameter list. Called in a list context, it returns the
4092 parameter list as an ordinary hash. This allows you to read the
4093 contents of the parameter list, but not to change it.
4095 When using this, the thing you must watch out for are multivalued CGI
4096 parameters. Because a hash cannot distinguish between scalar and
4097 list context, multivalued parameters will be returned as a packed
4098 string, separated by the "\0" (null) character. You must split this
4099 packed string in order to get at the individual values. This is the
4100 convention introduced long ago by Steve Brenner in his cgi-lib.pl
4101 module for Perl version 4.
4103 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
4104 function calls (also see the section on CGI-LIB compatibility).
4106 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
4108 $query->save(FILEHANDLE)
4110 This will write the current state of the form to the provided
4111 filehandle. You can read it back in by providing a filehandle
4112 to the new() method. Note that the filehandle can be a file, a pipe,
4115 The format of the saved file is:
4123 Both name and value are URL escaped. Multi-valued CGI parameters are
4124 represented as repeated names. A session record is delimited by a
4125 single = symbol. You can write out multiple records and read them
4126 back in with several calls to B<new>. You can do this across several
4127 sessions by opening the file in append mode, allowing you to create
4128 primitive guest books, or to keep a history of users' queries. Here's
4129 a short example of creating multiple session records:
4133 open (OUT,">>test.out") || die;
4135 foreach (0..$records) {
4137 $q->param(-name=>'counter',-value=>$_);
4142 # reopen for reading
4143 open (IN,"test.out") || die;
4145 my $q = new CGI(IN);
4146 print $q->param('counter'),"\n";
4149 The file format used for save/restore is identical to that used by the
4150 Whitehead Genome Center's data exchange format "Boulderio", and can be
4151 manipulated and even databased using Boulderio utilities. See
4153 http://stein.cshl.org/boulder/
4155 for further details.
4157 If you wish to use this method from the function-oriented (non-OO)
4158 interface, the exported name for this method is B<save_parameters()>.
4160 =head2 RETRIEVING CGI ERRORS
4162 Errors can occur while processing user input, particularly when
4163 processing uploaded files. When these errors occur, CGI will stop
4164 processing and return an empty parameter list. You can test for
4165 the existence and nature of errors using the I<cgi_error()> function.
4166 The error messages are formatted as HTTP status codes. You can either
4167 incorporate the error text into an HTML page, or use it as the value
4170 my $error = $q->cgi_error;
4172 print $q->header(-status=>$error),
4173 $q->start_html('Problems'),
4174 $q->h2('Request not processed'),
4179 When using the function-oriented interface (see the next section),
4180 errors may only occur the first time you call I<param()>. Be ready
4183 =head2 USING THE FUNCTION-ORIENTED INTERFACE
4185 To use the function-oriented interface, you must specify which CGI.pm
4186 routines or sets of routines to import into your script's namespace.
4187 There is a small overhead associated with this importation, but it
4190 use CGI <list of methods>;
4192 The listed methods will be imported into the current package; you can
4193 call them directly without creating a CGI object first. This example
4194 shows how to import the B<param()> and B<header()>
4195 methods, and then use them directly:
4197 use CGI 'param','header';
4198 print header('text/plain');
4199 $zipcode = param('zipcode');
4201 More frequently, you'll import common sets of functions by referring
4202 to the groups by name. All function sets are preceded with a ":"
4203 character as in ":html3" (for tags defined in the HTML 3 standard).
4205 Here is a list of the function sets you can import:
4211 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4216 Import all fill-out form generating methods, such as B<textfield()>.
4220 Import all methods that generate HTML 2.0 standard elements.
4224 Import all methods that generate HTML 3.0 elements (such as
4225 <table>, <super> and <sub>).
4229 Import all methods that generate HTML 4 elements (such as
4230 <abbrev>, <acronym> and <thead>).
4234 Import all methods that generate Netscape-specific HTML extensions.
4238 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4243 Import "standard" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.
4247 Import all the available methods. For the full list, see the CGI.pm
4248 code, where the variable %EXPORT_TAGS is defined.
4252 If you import a function name that is not part of CGI.pm, the module
4253 will treat it as a new HTML tag and generate the appropriate
4254 subroutine. You can then use it like any other HTML tag. This is to
4255 provide for the rapidly-evolving HTML "standard." For example, say
4256 Microsoft comes out with a new tag called <gradient> (which causes the
4257 user's desktop to be flooded with a rotating gradient fill until his
4258 machine reboots). You don't need to wait for a new version of CGI.pm
4259 to start using it immediately:
4261 use CGI qw/:standard :html3 gradient/;
4262 print gradient({-start=>'red',-end=>'blue'});
4264 Note that in the interests of execution speed CGI.pm does B<not> use
4265 the standard L<Exporter> syntax for specifying load symbols. This may
4266 change in the future.
4268 If you import any of the state-maintaining CGI or form-generating
4269 methods, a default CGI object will be created and initialized
4270 automatically the first time you use any of the methods that require
4271 one to be present. This includes B<param()>, B<textfield()>,
4272 B<submit()> and the like. (If you need direct access to the CGI
4273 object, you can find it in the global variable B<$CGI::Q>). By
4274 importing CGI.pm methods, you can create visually elegant scripts:
4276 use CGI qw/:standard/;
4279 start_html('Simple Script'),
4280 h1('Simple Script'),
4282 "What's your name? ",textfield('name'),p,
4283 "What's the combination?",
4284 checkbox_group(-name=>'words',
4285 -values=>['eenie','meenie','minie','moe'],
4286 -defaults=>['eenie','moe']),p,
4287 "What's your favorite color?",
4288 popup_menu(-name=>'color',
4289 -values=>['red','green','blue','chartreuse']),p,
4296 "Your name is ",em(param('name')),p,
4297 "The keywords are: ",em(join(", ",param('words'))),p,
4298 "Your favorite color is ",em(param('color')),".\n";
4304 In addition to the function sets, there are a number of pragmas that
4305 you can import. Pragmas, which are always preceded by a hyphen,
4306 change the way that CGI.pm functions in various ways. Pragmas,
4307 function sets, and individual functions can all be imported in the
4308 same use() line. For example, the following use statement imports the
4309 standard set of functions and enables debugging mode (pragma
4312 use CGI qw/:standard -debug/;
4314 The current list of pragmas is as follows:
4320 When you I<use CGI -any>, then any method that the query object
4321 doesn't recognize will be interpreted as a new HTML tag. This allows
4322 you to support the next I<ad hoc> Netscape or Microsoft HTML
4323 extension. This lets you go wild with new and unsupported tags:
4327 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4329 Since using <cite>any</cite> causes any mistyped method name
4330 to be interpreted as an HTML tag, use it with care or not at
4335 This causes the indicated autoloaded methods to be compiled up front,
4336 rather than deferred to later. This is useful for scripts that run
4337 for an extended period of time under FastCGI or mod_perl, and for
4338 those destined to be crunched by Malcom Beattie's Perl compiler. Use
4339 it in conjunction with the methods or method families you plan to use.
4341 use CGI qw(-compile :standard :html3);
4345 use CGI qw(-compile :all);
4347 Note that using the -compile pragma in this way will always have
4348 the effect of importing the compiled functions into the current
4349 namespace. If you want to compile without importing use the
4350 compile() method instead:
4355 This is particularly useful in a mod_perl environment, in which you
4356 might want to precompile all CGI routines in a startup script, and
4357 then import the functions individually in each mod_perl script.
4361 This makes CGI.pm not generating the hidden fields .submit
4362 and .cgifields. It is very useful if you don't want to
4363 have the hidden fields appear in the querystring in a GET method.
4364 For example, a search script generated this way will have
4365 a very nice url with search parameters for bookmarking.
4367 =item -no_undef_params
4369 This keeps CGI.pm from including undef params in the parameter list.
4373 By default, CGI.pm versions 2.69 and higher emit XHTML
4374 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4375 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4380 This makes CGI.pm produce a header appropriate for an NPH (no
4381 parsed header) script. You may need to do other things as well
4382 to tell the server that the script is NPH. See the discussion
4383 of NPH scripts below.
4385 =item -newstyle_urls
4387 Separate the name=value pairs in CGI parameter query strings with
4388 semicolons rather than ampersands. For example:
4390 ?name=fred;age=24;favorite_color=3
4392 Semicolon-delimited query strings are always accepted, but will not be
4393 emitted by self_url() and query_string() unless the -newstyle_urls
4394 pragma is specified.
4396 This became the default in version 2.64.
4398 =item -oldstyle_urls
4400 Separate the name=value pairs in CGI parameter query strings with
4401 ampersands rather than semicolons. This is no longer the default.
4405 This overrides the autoloader so that any function in your program
4406 that is not recognized is referred to CGI.pm for possible evaluation.
4407 This allows you to use all the CGI.pm functions without adding them to
4408 your symbol table, which is of concern for mod_perl users who are
4409 worried about memory consumption. I<Warning:> when
4410 I<-autoload> is in effect, you cannot use "poetry mode"
4411 (functions without the parenthesis). Use I<hr()> rather
4412 than I<hr>, or add something like I<use subs qw/hr p header/>
4413 to the top of your script.
4417 This turns off the command-line processing features. If you want to
4418 run a CGI.pm script from the command line to produce HTML, and you
4419 don't want it to read CGI parameters from the command line or STDIN,
4420 then use this pragma:
4422 use CGI qw(-no_debug :standard);
4426 This turns on full debugging. In addition to reading CGI arguments
4427 from the command-line processing, CGI.pm will pause and try to read
4428 arguments from STDIN, producing the message "(offline mode: enter
4429 name=value pairs on standard input)" features.
4431 See the section on debugging for more details.
4433 =item -private_tempfiles
4435 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4436 file to a temporary directory, then deletes the file when done.
4437 However, this opens the risk of eavesdropping as described in the file
4438 upload section. Another CGI script author could peek at this data
4439 during the upload, even if it is confidential information. On Unix
4440 systems, the -private_tempfiles pragma will cause the temporary file
4441 to be unlinked as soon as it is opened and before any data is written
4442 into it, reducing, but not eliminating the risk of eavesdropping
4443 (there is still a potential race condition). To make life harder for
4444 the attacker, the program chooses tempfile names by calculating a 32
4445 bit checksum of the incoming HTTP headers.
4447 To ensure that the temporary file cannot be read by other CGI scripts,
4448 use suEXEC or a CGI wrapper program to run your script. The temporary
4449 file is created with mode 0600 (neither world nor group readable).
4451 The temporary directory is selected using the following algorithm:
4453 1. if the current user (e.g. "nobody") has a directory named
4454 "tmp" in its home directory, use that (Unix systems only).
4456 2. if the environment variable TMPDIR exists, use the location
4459 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4460 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4462 Each of these locations is checked that it is a directory and is
4463 writable. If not, the algorithm tries the next choice.
4467 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4469 Many of the methods generate HTML tags. As described below, tag
4470 functions automatically generate both the opening and closing tags.
4473 print h1('Level 1 Header');
4477 <h1>Level 1 Header</h1>
4479 There will be some times when you want to produce the start and end
4480 tags yourself. In this case, you can use the form start_I<tag_name>
4481 and end_I<tag_name>, as in:
4483 print start_h1,'Level 1 Header',end_h1;
4485 With a few exceptions (described below), start_I<tag_name> and
4486 end_I<tag_name> functions are not generated automatically when you
4487 I<use CGI>. However, you can specify the tags you want to generate
4488 I<start/end> functions for by putting an asterisk in front of their
4489 name, or, alternatively, requesting either "start_I<tag_name>" or
4490 "end_I<tag_name>" in the import list.
4494 use CGI qw/:standard *table start_ul/;
4496 In this example, the following functions are generated in addition to
4501 =item 1. start_table() (generates a <table> tag)
4503 =item 2. end_table() (generates a </table> tag)
4505 =item 3. start_ul() (generates a <ul> tag)
4507 =item 4. end_ul() (generates a </ul> tag)
4511 =head1 GENERATING DYNAMIC DOCUMENTS
4513 Most of CGI.pm's functions deal with creating documents on the fly.
4514 Generally you will produce the HTTP header first, followed by the
4515 document itself. CGI.pm provides functions for generating HTTP
4516 headers of various types as well as for generating HTML. For creating
4517 GIF images, see the GD.pm module.
4519 Each of these functions produces a fragment of HTML or HTTP which you
4520 can print out directly so that it displays in the browser window,
4521 append to a string, or save to a file for later use.
4523 =head2 CREATING A STANDARD HTTP HEADER:
4525 Normally the first thing you will do in any CGI script is print out an
4526 HTTP header. This tells the browser what type of document to expect,
4527 and gives other optional information, such as the language, expiration
4528 date, and whether to cache the document. The header can also be
4529 manipulated for special purposes, such as server push and pay per view
4532 print $query->header;
4536 print $query->header('image/gif');
4540 print $query->header('text/html','204 No response');
4544 print $query->header(-type=>'image/gif',
4546 -status=>'402 Payment required',
4550 -attachment=>'foo.gif',
4553 header() returns the Content-type: header. You can provide your own
4554 MIME type if you choose, otherwise it defaults to text/html. An
4555 optional second parameter specifies the status code and a human-readable
4556 message. For example, you can specify 204, "No response" to create a
4557 script that tells the browser to do nothing at all.
4559 The last example shows the named argument style for passing arguments
4560 to the CGI methods using named parameters. Recognized parameters are
4561 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
4562 parameters will be stripped of their initial hyphens and turned into
4563 header fields, allowing you to specify any HTTP header you desire.
4564 Internal underscores will be turned into hyphens:
4566 print $query->header(-Content_length=>3002);
4568 Most browsers will not cache the output from CGI scripts. Every time
4569 the browser reloads the page, the script is invoked anew. You can
4570 change this behavior with the B<-expires> parameter. When you specify
4571 an absolute or relative expiration interval with this parameter, some
4572 browsers and proxy servers will cache the script's output until the
4573 indicated expiration date. The following forms are all valid for the
4576 +30s 30 seconds from now
4577 +10m ten minutes from now
4578 +1h one hour from now
4579 -1d yesterday (i.e. "ASAP!")
4582 +10y in ten years time
4583 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
4585 The B<-cookie> parameter generates a header that tells the browser to provide
4586 a "magic cookie" during all subsequent transactions with your script.
4587 Netscape cookies have a special format that includes interesting attributes
4588 such as expiration time. Use the cookie() method to create and retrieve
4591 The B<-nph> parameter, if set to a true value, will issue the correct
4592 headers to work with a NPH (no-parse-header) script. This is important
4593 to use with certain servers that expect all their scripts to be NPH.
4595 The B<-charset> parameter can be used to control the character set
4596 sent to the browser. If not provided, defaults to ISO-8859-1. As a
4597 side effect, this sets the charset() method as well.
4599 The B<-attachment> parameter can be used to turn the page into an
4600 attachment. Instead of displaying the page, some browsers will prompt
4601 the user to save it to disk. The value of the argument is the
4602 suggested name for the saved file. In order for this to work, you may
4603 have to set the B<-type> to "application/octet-stream".
4605 The B<-p3p> parameter will add a P3P tag to the outgoing header. The
4606 parameter can be an arrayref or a space-delimited string of P3P tags.
4609 print header(-p3p=>[qw(CAO DSP LAW CURa)]);
4610 print header(-p3p=>'CAO DSP LAW CURa');
4612 In either case, the outgoing header will be formatted as:
4614 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
4616 =head2 GENERATING A REDIRECTION HEADER
4618 print $query->redirect('http://somewhere.else/in/movie/land');
4620 Sometimes you don't want to produce a document yourself, but simply
4621 redirect the browser elsewhere, perhaps choosing a URL based on the
4622 time of day or the identity of the user.
4624 The redirect() function redirects the browser to a different URL. If
4625 you use redirection like this, you should B<not> print out a header as
4628 One hint I can offer is that relative links may not work correctly
4629 when you generate a redirection to another document on your site.
4630 This is due to a well-intentioned optimization that some servers use.
4631 The solution to this is to use the full URL (including the http: part)
4632 of the document you are redirecting to.
4634 You can also use named arguments:
4636 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4639 The B<-nph> parameter, if set to a true value, will issue the correct
4640 headers to work with a NPH (no-parse-header) script. This is important
4641 to use with certain servers, such as Microsoft Internet Explorer, which
4642 expect all their scripts to be NPH.
4644 =head2 CREATING THE HTML DOCUMENT HEADER
4646 print $query->start_html(-title=>'Secrets of the Pyramids',
4647 -author=>'fred@capricorn.org',
4650 -meta=>{'keywords'=>'pharaoh secret mummy',
4651 'copyright'=>'copyright 1996 King Tut'},
4652 -style=>{'src'=>'/styles/style1.css'},
4655 After creating the HTTP header, most CGI scripts will start writing
4656 out an HTML document. The start_html() routine creates the top of the
4657 page, along with a lot of optional information that controls the
4658 page's appearance and behavior.
4660 This method returns a canned HTML header and the opening <body> tag.
4661 All parameters are optional. In the named parameter form, recognized
4662 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4663 (see below for the explanation). Any additional parameters you
4664 provide, such as the Netscape unofficial BGCOLOR attribute, are added
4665 to the <body> tag. Additional parameters must be proceeded by a
4668 The argument B<-xbase> allows you to provide an HREF for the <base> tag
4669 different from the current location, as in
4671 -xbase=>"http://home.mcom.com/"
4673 All relative links will be interpreted relative to this tag.
4675 The argument B<-target> allows you to provide a default target frame
4676 for all the links and fill-out forms on the page. B<This is a
4677 non-standard HTTP feature which only works with Netscape browsers!>
4678 See the Netscape documentation on frames for details of how to
4681 -target=>"answer_window"
4683 All relative links will be interpreted relative to this tag.
4684 You add arbitrary meta information to the header with the B<-meta>
4685 argument. This argument expects a reference to an associative array
4686 containing name/value pairs of meta information. These will be turned
4687 into a series of header <meta> tags that look something like this:
4689 <meta name="keywords" content="pharaoh secret mummy">
4690 <meta name="description" content="copyright 1996 King Tut">
4692 To create an HTTP-EQUIV type of <meta> tag, use B<-head>, described
4695 The B<-style> argument is used to incorporate cascading stylesheets
4696 into your code. See the section on CASCADING STYLESHEETS for more
4699 The B<-lang> argument is used to incorporate a language attribute into
4700 the <html> tag. The default if not specified is "en-US" for US
4701 English. For example:
4703 print $q->start_html(-lang=>'fr-CA');
4705 To leave off the lang attribute, as you must do if you want to generate
4706 legal HTML 3.2 or earlier, pass the empty string (-lang=>'').
4708 The B<-encoding> argument can be used to specify the character set for
4709 XHTML. It defaults to iso-8859-1 if not specified.
4711 You can place other arbitrary HTML elements to the <head> section with the
4712 B<-head> tag. For example, to place the rarely-used <link> element in the
4713 head section, use this:
4715 print start_html(-head=>Link({-rel=>'next',
4716 -href=>'http://www.capricorn.com/s2.html'}));
4718 To incorporate multiple HTML elements into the <head> section, just pass an
4721 print start_html(-head=>[
4723 -href=>'http://www.capricorn.com/s2.html'}),
4724 Link({-rel=>'previous',
4725 -href=>'http://www.capricorn.com/s1.html'})
4729 And here's how to create an HTTP-EQUIV <meta> tag:
4731 print start_html(-head=>meta({-http_equiv => 'Content-Type',
4732 -content => 'text/html'}))
4735 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4736 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4737 to add Netscape JavaScript calls to your pages. B<-script> should
4738 point to a block of text containing JavaScript function definitions.
4739 This block will be placed within a <script> block inside the HTML (not
4740 HTTP) header. The block is placed in the header in order to give your
4741 page a fighting chance of having all its JavaScript functions in place
4742 even if the user presses the stop button before the page has loaded
4743 completely. CGI.pm attempts to format the script in such a way that
4744 JavaScript-naive browsers will not choke on the code: unfortunately
4745 there are some browsers, such as Chimera for Unix, that get confused
4748 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4749 code to execute when the page is respectively opened and closed by the
4750 browser. Usually these parameters are calls to functions defined in the
4754 print $query->header;
4756 // Ask a silly question
4757 function riddle_me_this() {
4758 var r = prompt("What walks on four legs in the morning, " +
4759 "two legs in the afternoon, " +
4760 "and three legs in the evening?");
4763 // Get a silly answer
4764 function response(answer) {
4765 if (answer == "man")
4766 alert("Right you are!");
4768 alert("Wrong! Guess again.");
4771 print $query->start_html(-title=>'The Riddle of the Sphinx',
4774 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4775 browsers that do not have JavaScript (or browsers where JavaScript is turned
4778 Netscape 3.0 recognizes several attributes of the <script> tag,
4779 including LANGUAGE and SRC. The latter is particularly interesting,
4780 as it allows you to keep the JavaScript code in a file or CGI script
4781 rather than cluttering up each page with the source. To use these
4782 attributes pass a HASH reference in the B<-script> parameter containing
4783 one or more of -language, -src, or -code:
4785 print $q->start_html(-title=>'The Riddle of the Sphinx',
4786 -script=>{-language=>'JAVASCRIPT',
4787 -src=>'/javascript/sphinx.js'}
4790 print $q->(-title=>'The Riddle of the Sphinx',
4791 -script=>{-language=>'PERLSCRIPT',
4792 -code=>'print "hello world!\n;"'}
4796 A final feature allows you to incorporate multiple <script> sections into the
4797 header. Just pass the list of script sections as an array reference.
4798 this allows you to specify different source files for different dialects
4799 of JavaScript. Example:
4801 print $q->start_html(-title=>'The Riddle of the Sphinx',
4803 { -language => 'JavaScript1.0',
4804 -src => '/javascript/utilities10.js'
4806 { -language => 'JavaScript1.1',
4807 -src => '/javascript/utilities11.js'
4809 { -language => 'JavaScript1.2',
4810 -src => '/javascript/utilities12.js'
4812 { -language => 'JavaScript28.2',
4813 -src => '/javascript/utilities219.js'
4818 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4822 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4824 for more information about JavaScript.
4826 The old-style positional parameters are as follows:
4830 =item B<Parameters:>
4838 The author's e-mail address (will create a <link rev="MADE"> tag if present
4842 A 'true' flag if you want to include a <base> tag in the header. This
4843 helps resolve relative addresses to absolute ones when the document is moved,
4844 but makes the document hierarchy non-portable. Use with care!
4848 Any other parameters you want to include in the <body> tag. This is a good
4849 place to put Netscape extensions, such as colors and wallpaper patterns.
4853 =head2 ENDING THE HTML DOCUMENT:
4855 print $query->end_html
4857 This ends an HTML document by printing the </body></html> tags.
4859 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4861 $myself = $query->self_url;
4862 print q(<a href="$myself">I'm talking to myself.</a>);
4864 self_url() will return a URL, that, when selected, will reinvoke
4865 this script with all its state information intact. This is most
4866 useful when you want to jump around within the document using
4867 internal anchors but you don't want to disrupt the current contents
4868 of the form(s). Something like this will do the trick.
4870 $myself = $query->self_url;
4871 print "<a href=\"$myself#table1\">See table 1</a>";
4872 print "<a href=\"$myself#table2\">See table 2</a>";
4873 print "<a href=\"$myself#yourself\">See for yourself</a>";
4875 If you want more control over what's returned, using the B<url()>
4878 You can also retrieve the unprocessed query string with query_string():
4880 $the_string = $query->query_string;
4882 =head2 OBTAINING THE SCRIPT'S URL
4884 $full_url = $query->url();
4885 $full_url = $query->url(-full=>1); #alternative syntax
4886 $relative_url = $query->url(-relative=>1);
4887 $absolute_url = $query->url(-absolute=>1);
4888 $url_with_path = $query->url(-path_info=>1);
4889 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4890 $netloc = $query->url(-base => 1);
4892 B<url()> returns the script's URL in a variety of formats. Called
4893 without any arguments, it returns the full form of the URL, including
4894 host name and port number
4896 http://your.host.com/path/to/script.cgi
4898 You can modify this format with the following named arguments:
4904 If true, produce an absolute URL, e.g.
4910 Produce a relative URL. This is useful if you want to reinvoke your
4911 script with different parameters. For example:
4917 Produce the full URL, exactly as if called without any arguments.
4918 This overrides the -relative and -absolute arguments.
4920 =item B<-path> (B<-path_info>)
4922 Append the additional path information to the URL. This can be
4923 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
4924 is provided as a synonym.
4926 =item B<-query> (B<-query_string>)
4928 Append the query string to the URL. This can be combined with
4929 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
4934 Generate just the protocol and net location, as in http://www.foo.com:8000
4938 =head2 MIXING POST AND URL PARAMETERS
4940 $color = $query->url_param('color');
4942 It is possible for a script to receive CGI parameters in the URL as
4943 well as in the fill-out form by creating a form that POSTs to a URL
4944 containing a query string (a "?" mark followed by arguments). The
4945 B<param()> method will always return the contents of the POSTed
4946 fill-out form, ignoring the URL's query string. To retrieve URL
4947 parameters, call the B<url_param()> method. Use it in the same way as
4948 B<param()>. The main difference is that it allows you to read the
4949 parameters, but not set them.
4952 Under no circumstances will the contents of the URL query string
4953 interfere with similarly-named CGI parameters in POSTed forms. If you
4954 try to mix a URL query string with a form submitted with the GET
4955 method, the results will not be what you expect.
4957 =head1 CREATING STANDARD HTML ELEMENTS:
4959 CGI.pm defines general HTML shortcut methods for most, if not all of
4960 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
4961 HTML element and return a fragment of HTML text that you can then
4962 print or manipulate as you like. Each shortcut returns a fragment of
4963 HTML code that you can append to a string, save to a file, or, most
4964 commonly, print out so that it displays in the browser window.
4966 This example shows how to use the HTML methods:
4969 print $q->blockquote(
4970 "Many years ago on the island of",
4971 $q->a({href=>"http://crete.org/"},"Crete"),
4972 "there lived a Minotaur named",
4973 $q->strong("Fred."),
4977 This results in the following HTML code (extra newlines have been
4978 added for readability):
4981 Many years ago on the island of
4982 <a href="http://crete.org/">Crete</a> there lived
4983 a minotaur named <strong>Fred.</strong>
4987 If you find the syntax for calling the HTML shortcuts awkward, you can
4988 import them into your namespace and dispense with the object syntax
4989 completely (see the next section for more details):
4991 use CGI ':standard';
4993 "Many years ago on the island of",
4994 a({href=>"http://crete.org/"},"Crete"),
4995 "there lived a minotaur named",
5000 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
5002 The HTML methods will accept zero, one or multiple arguments. If you
5003 provide no arguments, you get a single tag:
5007 If you provide one or more string arguments, they are concatenated
5008 together with spaces and placed between opening and closing tags:
5010 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
5012 If the first argument is an associative array reference, then the keys
5013 and values of the associative array become the HTML tag's attributes:
5015 print a({-href=>'fred.html',-target=>'_new'},
5016 "Open a new frame");
5018 <a href="fred.html",target="_new">Open a new frame</a>
5020 You may dispense with the dashes in front of the attribute names if
5023 print img {src=>'fred.gif',align=>'LEFT'};
5025 <img align="LEFT" src="fred.gif">
5027 Sometimes an HTML tag attribute has no argument. For example, ordered
5028 lists can be marked as COMPACT. The syntax for this is an argument that
5029 that points to an undef string:
5031 print ol({compact=>undef},li('one'),li('two'),li('three'));
5033 Prior to CGI.pm version 2.41, providing an empty ('') string as an
5034 attribute argument was the same as providing undef. However, this has
5035 changed in order to accommodate those who want to create tags of the form
5036 <img alt="">. The difference is shown in these two pieces of code:
5039 img({alt=>undef}) <img alt>
5040 img({alt=>''}) <img alt="">
5042 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
5044 One of the cool features of the HTML shortcuts is that they are
5045 distributive. If you give them an argument consisting of a
5046 B<reference> to a list, the tag will be distributed across each
5047 element of the list. For example, here's one way to make an ordered
5051 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
5054 This example will result in HTML output that looks like this:
5057 <li type="disc">Sneezy</li>
5058 <li type="disc">Doc</li>
5059 <li type="disc">Sleepy</li>
5060 <li type="disc">Happy</li>
5063 This is extremely useful for creating tables. For example:
5065 print table({-border=>undef},
5066 caption('When Should You Eat Your Vegetables?'),
5067 Tr({-align=>CENTER,-valign=>TOP},
5069 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
5070 td(['Tomatoes' , 'no', 'yes', 'yes']),
5071 td(['Broccoli' , 'no', 'no', 'yes']),
5072 td(['Onions' , 'yes','yes', 'yes'])
5077 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
5079 Consider this bit of code:
5081 print blockquote(em('Hi'),'mom!'));
5083 It will ordinarily return the string that you probably expect, namely:
5085 <blockquote><em>Hi</em> mom!</blockquote>
5087 Note the space between the element "Hi" and the element "mom!".
5088 CGI.pm puts the extra space there using array interpolation, which is
5089 controlled by the magic $" variable. Sometimes this extra space is
5090 not what you want, for example, when you are trying to align a series
5091 of images. In this case, you can simply change the value of $" to an
5096 print blockquote(em('Hi'),'mom!'));
5099 I suggest you put the code in a block as shown here. Otherwise the
5100 change to $" will affect all subsequent code until you explicitly
5103 =head2 NON-STANDARD HTML SHORTCUTS
5105 A few HTML tags don't follow the standard pattern for various
5108 B<comment()> generates an HTML comment (<!-- comment -->). Call it
5111 print comment('here is my comment');
5113 Because of conflicts with built-in Perl functions, the following functions
5114 begin with initial caps:
5123 In addition, start_html(), end_html(), start_form(), end_form(),
5124 start_multipart_form() and all the fill-out form tags are special.
5125 See their respective sections.
5127 =head2 AUTOESCAPING HTML
5129 By default, all HTML that is emitted by the form-generating functions
5130 is passed through a function called escapeHTML():
5134 =item $escaped_string = escapeHTML("unescaped string");
5136 Escape HTML formatting characters in a string.
5140 Provided that you have specified a character set of ISO-8859-1 (the
5141 default), the standard HTML escaping rules will be used. The "<"
5142 character becomes "<", ">" becomes ">", "&" becomes "&", and
5143 the quote character becomes """. In addition, the hexadecimal
5144 0x8b and 0x9b characters, which some browsers incorrectly interpret
5145 as the left and right angle-bracket characters, are replaced by their
5146 numeric character entities ("‹" and "›"). If you manually change
5147 the charset, either by calling the charset() method explicitly or by
5148 passing a -charset argument to header(), then B<all> characters will
5149 be replaced by their numeric entities, since CGI.pm has no lookup
5150 table for all the possible encodings.
5152 The automatic escaping does not apply to other shortcuts, such as
5153 h1(). You should call escapeHTML() yourself on untrusted data in
5154 order to protect your pages against nasty tricks that people may enter
5155 into guestbooks, etc.. To change the character set, use charset().
5156 To turn autoescaping off completely, use autoEscape(0):
5160 =item $charset = charset([$charset]);
5162 Get or set the current character set.
5164 =item $flag = autoEscape([$flag]);
5166 Get or set the value of the autoescape flag.
5170 =head2 PRETTY-PRINTING HTML
5172 By default, all the HTML produced by these functions comes out as one
5173 long line without carriage returns or indentation. This is yuck, but
5174 it does reduce the size of the documents by 10-20%. To get
5175 pretty-printed output, please use L<CGI::Pretty>, a subclass
5176 contributed by Brian Paulsen.
5178 =head1 CREATING FILL-OUT FORMS:
5180 I<General note> The various form-creating methods all return strings
5181 to the caller, containing the tag or tags that will create the requested
5182 form element. You are responsible for actually printing out these strings.
5183 It's set up this way so that you can place formatting tags
5184 around the form elements.
5186 I<Another note> The default values that you specify for the forms are only
5187 used the B<first> time the script is invoked (when there is no query
5188 string). On subsequent invocations of the script (when there is a query
5189 string), the former values are used even if they are blank.
5191 If you want to change the value of a field from its previous value, you have two
5194 (1) call the param() method to set it.
5196 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
5197 This forces the default value to be used, regardless of the previous value:
5199 print $query->textfield(-name=>'field_name',
5200 -default=>'starting value',
5205 I<Yet another note> By default, the text and labels of form elements are
5206 escaped according to HTML rules. This means that you can safely use
5207 "<CLICK ME>" as the label for a button. However, it also interferes with
5208 your ability to incorporate special HTML character sequences, such as Á,
5209 into your fields. If you wish to turn off automatic escaping, call the
5210 autoEscape() method with a false value immediately after creating the CGI object:
5213 $query->autoEscape(undef);
5215 =head2 CREATING AN ISINDEX TAG
5217 print $query->isindex(-action=>$action);
5221 print $query->isindex($action);
5223 Prints out an <isindex> tag. Not very exciting. The parameter
5224 -action specifies the URL of the script to process the query. The
5225 default is to process the query with the current script.
5227 =head2 STARTING AND ENDING A FORM
5229 print $query->start_form(-method=>$method,
5231 -enctype=>$encoding);
5232 <... various form stuff ...>
5233 print $query->endform;
5237 print $query->start_form($method,$action,$encoding);
5238 <... various form stuff ...>
5239 print $query->endform;
5241 start_form() will return a <form> tag with the optional method,
5242 action and form encoding that you specify. The defaults are:
5246 enctype: application/x-www-form-urlencoded
5248 endform() returns the closing </form> tag.
5250 Start_form()'s enctype argument tells the browser how to package the various
5251 fields of the form before sending the form to the server. Two
5252 values are possible:
5254 B<Note:> This method was previously named startform(), and startform()
5255 is still recognized as an alias.
5259 =item B<application/x-www-form-urlencoded>
5261 This is the older type of encoding used by all browsers prior to
5262 Netscape 2.0. It is compatible with many CGI scripts and is
5263 suitable for short fields containing text data. For your
5264 convenience, CGI.pm stores the name of this encoding
5265 type in B<&CGI::URL_ENCODED>.
5267 =item B<multipart/form-data>
5269 This is the newer type of encoding introduced by Netscape 2.0.
5270 It is suitable for forms that contain very large fields or that
5271 are intended for transferring binary data. Most importantly,
5272 it enables the "file upload" feature of Netscape 2.0 forms. For
5273 your convenience, CGI.pm stores the name of this encoding type
5274 in B<&CGI::MULTIPART>
5276 Forms that use this type of encoding are not easily interpreted
5277 by CGI scripts unless they use CGI.pm or another library designed
5282 For compatibility, the start_form() method uses the older form of
5283 encoding by default. If you want to use the newer form of encoding
5284 by default, you can call B<start_multipart_form()> instead of
5287 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
5288 for use with JavaScript. The -name parameter gives the
5289 form a name so that it can be identified and manipulated by
5290 JavaScript functions. -onSubmit should point to a JavaScript
5291 function that will be executed just before the form is submitted to your
5292 server. You can use this opportunity to check the contents of the form
5293 for consistency and completeness. If you find something wrong, you
5294 can put up an alert box or maybe fix things up yourself. You can
5295 abort the submission by returning false from this function.
5297 Usually the bulk of JavaScript functions are defined in a <script>
5298 block in the HTML header and -onSubmit points to one of these function
5299 call. See start_html() for details.
5301 =head2 CREATING A TEXT FIELD
5303 print $query->textfield(-name=>'field_name',
5304 -default=>'starting value',
5309 print $query->textfield('field_name','starting value',50,80);
5311 textfield() will return a text input field.
5319 The first parameter is the required name for the field (-name).
5323 The optional second parameter is the default starting value for the field
5324 contents (-default).
5328 The optional third parameter is the size of the field in
5333 The optional fourth parameter is the maximum number of characters the
5334 field will accept (-maxlength).
5338 As with all these methods, the field will be initialized with its
5339 previous contents from earlier invocations of the script.
5340 When the form is processed, the value of the text field can be
5343 $value = $query->param('foo');
5345 If you want to reset it from its initial value after the script has been
5346 called once, you can do so like this:
5348 $query->param('foo',"I'm taking over this value!");
5350 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
5351 value, you can force its current value by using the -override (alias -force)
5354 print $query->textfield(-name=>'field_name',
5355 -default=>'starting value',
5360 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
5361 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
5362 parameters to register JavaScript event handlers. The onChange
5363 handler will be called whenever the user changes the contents of the
5364 text field. You can do text validation if you like. onFocus and
5365 onBlur are called respectively when the insertion point moves into and
5366 out of the text field. onSelect is called when the user changes the
5367 portion of the text that is selected.
5369 =head2 CREATING A BIG TEXT FIELD
5371 print $query->textarea(-name=>'foo',
5372 -default=>'starting value',
5378 print $query->textarea('foo','starting value',10,50);
5380 textarea() is just like textfield, but it allows you to specify
5381 rows and columns for a multiline text entry box. You can provide
5382 a starting value for the field, which can be long and contain
5385 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
5386 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
5387 recognized. See textfield().
5389 =head2 CREATING A PASSWORD FIELD
5391 print $query->password_field(-name=>'secret',
5392 -value=>'starting value',
5397 print $query->password_field('secret','starting value',50,80);
5399 password_field() is identical to textfield(), except that its contents
5400 will be starred out on the web page.
5402 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5403 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5404 recognized. See textfield().
5406 =head2 CREATING A FILE UPLOAD FIELD
5408 print $query->filefield(-name=>'uploaded_file',
5409 -default=>'starting value',
5414 print $query->filefield('uploaded_file','starting value',50,80);
5416 filefield() will return a file upload field for Netscape 2.0 browsers.
5417 In order to take full advantage of this I<you must use the new
5418 multipart encoding scheme> for the form. You can do this either
5419 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5420 or by calling the new method B<start_multipart_form()> instead of
5421 vanilla B<start_form()>.
5429 The first parameter is the required name for the field (-name).
5433 The optional second parameter is the starting value for the field contents
5434 to be used as the default file name (-default).
5436 For security reasons, browsers don't pay any attention to this field,
5437 and so the starting value will always be blank. Worse, the field
5438 loses its "sticky" behavior and forgets its previous contents. The
5439 starting value field is called for in the HTML specification, however,
5440 and possibly some browser will eventually provide support for it.
5444 The optional third parameter is the size of the field in
5449 The optional fourth parameter is the maximum number of characters the
5450 field will accept (-maxlength).
5454 When the form is processed, you can retrieve the entered filename
5457 $filename = $query->param('uploaded_file');
5459 Different browsers will return slightly different things for the
5460 name. Some browsers return the filename only. Others return the full
5461 path to the file, using the path conventions of the user's machine.
5462 Regardless, the name returned is always the name of the file on the
5463 I<user's> machine, and is unrelated to the name of the temporary file
5464 that CGI.pm creates during upload spooling (see below).
5466 The filename returned is also a file handle. You can read the contents
5467 of the file using standard Perl file reading calls:
5469 # Read a text file and print it out
5470 while (<$filename>) {
5474 # Copy a binary file to somewhere safe
5475 open (OUTFILE,">>/usr/local/web/users/feedback");
5476 while ($bytesread=read($filename,$buffer,1024)) {
5477 print OUTFILE $buffer;
5480 However, there are problems with the dual nature of the upload fields.
5481 If you C<use strict>, then Perl will complain when you try to use a
5482 string as a filehandle. You can get around this by placing the file
5483 reading code in a block containing the C<no strict> pragma. More
5484 seriously, it is possible for the remote user to type garbage into the
5485 upload field, in which case what you get from param() is not a
5486 filehandle at all, but a string.
5488 To be safe, use the I<upload()> function (new in version 2.47). When
5489 called with the name of an upload field, I<upload()> returns a
5490 filehandle, or undef if the parameter is not a valid filehandle.
5492 $fh = $query->upload('uploaded_file');
5497 In an array context, upload() will return an array of filehandles.
5498 This makes it possible to create forms that use the same name for
5499 multiple upload fields.
5501 This is the recommended idiom.
5503 When a file is uploaded the browser usually sends along some
5504 information along with it in the format of headers. The information
5505 usually includes the MIME content type. Future browsers may send
5506 other information as well (such as modification date and size). To
5507 retrieve this information, call uploadInfo(). It returns a reference to
5508 an associative array containing all the document headers.
5510 $filename = $query->param('uploaded_file');
5511 $type = $query->uploadInfo($filename)->{'Content-Type'};
5512 unless ($type eq 'text/html') {
5513 die "HTML FILES ONLY!";
5516 If you are using a machine that recognizes "text" and "binary" data
5517 modes, be sure to understand when and how to use them (see the Camel book).
5518 Otherwise you may find that binary files are corrupted during file
5521 There are occasionally problems involving parsing the uploaded file.
5522 This usually happens when the user presses "Stop" before the upload is
5523 finished. In this case, CGI.pm will return undef for the name of the
5524 uploaded file and set I<cgi_error()> to the string "400 Bad request
5525 (malformed multipart POST)". This error message is designed so that
5526 you can incorporate it into a status code to be sent to the browser.
5529 $file = $query->upload('uploaded_file');
5530 if (!$file && $query->cgi_error) {
5531 print $query->header(-status=>$query->cgi_error);
5535 You are free to create a custom HTML page to complain about the error,
5538 If you are using CGI.pm on a Windows platform and find that binary
5539 files get slightly larger when uploaded but that text files remain the
5540 same, then you have forgotten to activate binary mode on the output
5541 filehandle. Be sure to call binmode() on any handle that you create
5542 to write the uploaded file to disk.
5544 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5545 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5546 recognized. See textfield() for details.
5548 =head2 CREATING A POPUP MENU
5550 print $query->popup_menu('menu_name',
5551 ['eenie','meenie','minie'],
5556 %labels = ('eenie'=>'your first choice',
5557 'meenie'=>'your second choice',
5558 'minie'=>'your third choice');
5559 %attributes = ('eenie'=>{'class'=>'class of first choice'});
5560 print $query->popup_menu('menu_name',
5561 ['eenie','meenie','minie'],
5562 'meenie',\%labels,\%attributes);
5564 -or (named parameter style)-
5566 print $query->popup_menu(-name=>'menu_name',
5567 -values=>['eenie','meenie','minie'],
5570 -attributes=>\%attributes);
5572 popup_menu() creates a menu.
5578 The required first argument is the menu's name (-name).
5582 The required second argument (-values) is an array B<reference>
5583 containing the list of menu items in the menu. You can pass the
5584 method an anonymous array, as shown in the example, or a reference to
5585 a named array, such as "\@foo".
5589 The optional third parameter (-default) is the name of the default
5590 menu choice. If not specified, the first item will be the default.
5591 The values of the previous choice will be maintained across queries.
5595 The optional fourth parameter (-labels) is provided for people who
5596 want to use different values for the user-visible label inside the
5597 popup menu and the value returned to your script. It's a pointer to an
5598 associative array relating menu values to user-visible labels. If you
5599 leave this parameter blank, the menu values will be displayed by
5600 default. (You can also leave a label undefined if you want to).
5604 The optional fifth parameter (-attributes) is provided to assign
5605 any of the common HTML attributes to an individual menu item. It's
5606 a pointer to an associative array relating menu values to another
5607 associative array with the attribute's name as the key and the
5608 attribute's value as the value.
5612 When the form is processed, the selected value of the popup menu can
5615 $popup_menu_value = $query->param('menu_name');
5617 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
5618 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5619 B<-onBlur>. See the textfield() section for details on when these
5620 handlers are called.
5622 =head2 CREATING AN OPTION GROUP
5624 Named parameter style
5626 print $query->popup_menu(-name=>'menu_name',
5627 -values=>[qw/eenie meenie minie/,
5628 $q->optgroup(-name=>'optgroup_name',
5629 -values ['moe','catch'],
5630 -attributes=>{'catch'=>{'class'=>'red'}}),
5631 -labels=>{'eenie'=>'one',
5634 -default=>'meenie');
5637 print $query->popup_menu('menu_name',
5638 ['eenie','meenie','minie',
5639 $q->optgroup('optgroup_name', ['moe', 'catch'],
5640 {'catch'=>{'class'=>'red'}})],'meenie',
5641 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
5643 optgroup creates an option group within a popup menu.
5649 The required first argument (B<-name>) is the label attribute of the
5650 optgroup and is B<not> inserted in the parameter list of the query.
5654 The required second argument (B<-values>) is an array reference
5655 containing the list of menu items in the menu. You can pass the
5656 method an anonymous array, as shown in the example, or a reference
5657 to a named array, such as \@foo. If you pass a HASH reference,
5658 the keys will be used for the menu values, and the values will be
5659 used for the menu labels (see -labels below).
5663 The optional third parameter (B<-labels>) allows you to pass a reference
5664 to an associative array containing user-visible labels for one or more
5665 of the menu items. You can use this when you want the user to see one
5666 menu string, but have the browser return your program a different one.
5667 If you don't specify this, the value string will be used instead
5668 ("eenie", "meenie" and "minie" in this example). This is equivalent
5669 to using a hash reference for the -values parameter.
5673 An optional fourth parameter (B<-labeled>) can be set to a true value
5674 and indicates that the values should be used as the label attribute
5675 for each option element within the optgroup.
5679 An optional fifth parameter (-novals) can be set to a true value and
5680 indicates to suppress the val attribut in each option element within
5683 See the discussion on optgroup at W3C
5684 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
5689 An optional sixth parameter (-attributes) is provided to assign
5690 any of the common HTML attributes to an individual menu item. It's
5691 a pointer to an associative array relating menu values to another
5692 associative array with the attribute's name as the key and the
5693 attribute's value as the value.
5695 =head2 CREATING A SCROLLING LIST
5697 print $query->scrolling_list('list_name',
5698 ['eenie','meenie','minie','moe'],
5699 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
5702 print $query->scrolling_list('list_name',
5703 ['eenie','meenie','minie','moe'],
5704 ['eenie','moe'],5,'true',
5705 \%labels,%attributes);
5709 print $query->scrolling_list(-name=>'list_name',
5710 -values=>['eenie','meenie','minie','moe'],
5711 -default=>['eenie','moe'],
5715 -attributes=>\%attributes);
5717 scrolling_list() creates a scrolling list.
5721 =item B<Parameters:>
5725 The first and second arguments are the list name (-name) and values
5726 (-values). As in the popup menu, the second argument should be an
5731 The optional third argument (-default) can be either a reference to a
5732 list containing the values to be selected by default, or can be a
5733 single value to select. If this argument is missing or undefined,
5734 then nothing is selected when the list first appears. In the named
5735 parameter version, you can use the synonym "-defaults" for this
5740 The optional fourth argument is the size of the list (-size).
5744 The optional fifth argument can be set to true to allow multiple
5745 simultaneous selections (-multiple). Otherwise only one selection
5746 will be allowed at a time.
5750 The optional sixth argument is a pointer to an associative array
5751 containing long user-visible labels for the list items (-labels).
5752 If not provided, the values will be displayed.
5756 The optional sixth parameter (-attributes) is provided to assign
5757 any of the common HTML attributes to an individual menu item. It's
5758 a pointer to an associative array relating menu values to another
5759 associative array with the attribute's name as the key and the
5760 attribute's value as the value.
5762 When this form is processed, all selected list items will be returned as
5763 a list under the parameter name 'list_name'. The values of the
5764 selected items can be retrieved with:
5766 @selected = $query->param('list_name');
5770 JAVASCRIPTING: scrolling_list() recognizes the following event
5771 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5772 and B<-onBlur>. See textfield() for the description of when these
5773 handlers are called.
5775 =head2 CREATING A GROUP OF RELATED CHECKBOXES
5777 print $query->checkbox_group(-name=>'group_name',
5778 -values=>['eenie','meenie','minie','moe'],
5779 -default=>['eenie','moe'],
5782 -attributes=>\%attributes);
5784 print $query->checkbox_group('group_name',
5785 ['eenie','meenie','minie','moe'],
5786 ['eenie','moe'],'true',\%labels,
5787 {'moe'=>{'class'=>'red'}});
5789 HTML3-COMPATIBLE BROWSERS ONLY:
5791 print $query->checkbox_group(-name=>'group_name',
5792 -values=>['eenie','meenie','minie','moe'],
5793 -rows=2,-columns=>2);
5796 checkbox_group() creates a list of checkboxes that are related
5801 =item B<Parameters:>
5805 The first and second arguments are the checkbox name and values,
5806 respectively (-name and -values). As in the popup menu, the second
5807 argument should be an array reference. These values are used for the
5808 user-readable labels printed next to the checkboxes as well as for the
5809 values passed to your script in the query string.
5813 The optional third argument (-default) can be either a reference to a
5814 list containing the values to be checked by default, or can be a
5815 single value to checked. If this argument is missing or undefined,
5816 then nothing is selected when the list first appears.
5820 The optional fourth argument (-linebreak) can be set to true to place
5821 line breaks between the checkboxes so that they appear as a vertical
5822 list. Otherwise, they will be strung together on a horizontal line.
5826 The optional fifth argument is a pointer to an associative array
5827 relating the checkbox values to the user-visible labels that will
5828 be printed next to them (-labels). If not provided, the values will
5829 be used as the default.
5833 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5834 the optional parameters B<-rows>, and B<-columns>. These parameters
5835 cause checkbox_group() to return an HTML3 compatible table containing
5836 the checkbox group formatted with the specified number of rows and
5837 columns. You can provide just the -columns parameter if you wish;
5838 checkbox_group will calculate the correct number of rows for you.
5842 The optional sixth parameter (-attributes) is provided to assign
5843 any of the common HTML attributes to an individual menu item. It's
5844 a pointer to an associative array relating menu values to another
5845 associative array with the attribute's name as the key and the
5846 attribute's value as the value.
5848 To include row and column headings in the returned table, you
5849 can use the B<-rowheaders> and B<-colheaders> parameters. Both
5850 of these accept a pointer to an array of headings to use.
5851 The headings are just decorative. They don't reorganize the
5852 interpretation of the checkboxes -- they're still a single named
5857 When the form is processed, all checked boxes will be returned as
5858 a list under the parameter name 'group_name'. The values of the
5859 "on" checkboxes can be retrieved with:
5861 @turned_on = $query->param('group_name');
5863 The value returned by checkbox_group() is actually an array of button
5864 elements. You can capture them and use them within tables, lists,
5865 or in other creative ways:
5867 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
5868 &use_in_creative_way(@h);
5870 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
5871 parameter. This specifies a JavaScript code fragment or
5872 function call to be executed every time the user clicks on
5873 any of the buttons in the group. You can retrieve the identity
5874 of the particular button clicked on using the "this" variable.
5876 =head2 CREATING A STANDALONE CHECKBOX
5878 print $query->checkbox(-name=>'checkbox_name',
5881 -label=>'CLICK ME');
5885 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
5887 checkbox() is used to create an isolated checkbox that isn't logically
5888 related to any others.
5892 =item B<Parameters:>
5896 The first parameter is the required name for the checkbox (-name). It
5897 will also be used for the user-readable label printed next to the
5902 The optional second parameter (-checked) specifies that the checkbox
5903 is turned on by default. Synonyms are -selected and -on.
5907 The optional third parameter (-value) specifies the value of the
5908 checkbox when it is checked. If not provided, the word "on" is
5913 The optional fourth parameter (-label) is the user-readable label to
5914 be attached to the checkbox. If not provided, the checkbox name is
5919 The value of the checkbox can be retrieved using:
5921 $turned_on = $query->param('checkbox_name');
5923 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
5924 parameter. See checkbox_group() for further details.
5926 =head2 CREATING A RADIO BUTTON GROUP
5928 print $query->radio_group(-name=>'group_name',
5929 -values=>['eenie','meenie','minie'],
5933 -attributes=>\%attributes);
5937 print $query->radio_group('group_name',['eenie','meenie','minie'],
5938 'meenie','true',\%labels,\%attributes);
5941 HTML3-COMPATIBLE BROWSERS ONLY:
5943 print $query->radio_group(-name=>'group_name',
5944 -values=>['eenie','meenie','minie','moe'],
5945 -rows=2,-columns=>2);
5947 radio_group() creates a set of logically-related radio buttons
5948 (turning one member of the group on turns the others off)
5952 =item B<Parameters:>
5956 The first argument is the name of the group and is required (-name).
5960 The second argument (-values) is the list of values for the radio
5961 buttons. The values and the labels that appear on the page are
5962 identical. Pass an array I<reference> in the second argument, either
5963 using an anonymous array, as shown, or by referencing a named array as
5968 The optional third parameter (-default) is the name of the default
5969 button to turn on. If not specified, the first item will be the
5970 default. You can provide a nonexistent button name, such as "-" to
5971 start up with no buttons selected.
5975 The optional fourth parameter (-linebreak) can be set to 'true' to put
5976 line breaks between the buttons, creating a vertical list.
5980 The optional fifth parameter (-labels) is a pointer to an associative
5981 array relating the radio button values to user-visible labels to be
5982 used in the display. If not provided, the values themselves are
5987 B<HTML3-compatible browsers> (such as Netscape) can take advantage
5989 parameters B<-rows>, and B<-columns>. These parameters cause
5990 radio_group() to return an HTML3 compatible table containing
5991 the radio group formatted with the specified number of rows
5992 and columns. You can provide just the -columns parameter if you
5993 wish; radio_group will calculate the correct number of rows
5998 The optional sixth parameter (-attributes) is provided to assign
5999 any of the common HTML attributes to an individual menu item. It's
6000 a pointer to an associative array relating menu values to another
6001 associative array with the attribute's name as the key and the
6002 attribute's value as the value.
6004 To include row and column headings in the returned table, you
6005 can use the B<-rowheader> and B<-colheader> parameters. Both
6006 of these accept a pointer to an array of headings to use.
6007 The headings are just decorative. They don't reorganize the
6008 interpretation of the radio buttons -- they're still a single named
6013 When the form is processed, the selected radio button can
6016 $which_radio_button = $query->param('group_name');
6018 The value returned by radio_group() is actually an array of button
6019 elements. You can capture them and use them within tables, lists,
6020 or in other creative ways:
6022 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
6023 &use_in_creative_way(@h);
6025 =head2 CREATING A SUBMIT BUTTON
6027 print $query->submit(-name=>'button_name',
6032 print $query->submit('button_name','value');
6034 submit() will create the query submission button. Every form
6035 should have one of these.
6039 =item B<Parameters:>
6043 The first argument (-name) is optional. You can give the button a
6044 name if you have several submission buttons in your form and you want
6045 to distinguish between them. The name will also be used as the
6046 user-visible label. Be aware that a few older browsers don't deal with this correctly and
6047 B<never> send back a value from a button.
6051 The second argument (-value) is also optional. This gives the button
6052 a value that will be passed to your script in the query string.
6056 You can figure out which button was pressed by using different
6057 values for each one:
6059 $which_one = $query->param('button_name');
6061 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
6062 parameter. See checkbox_group() for further details.
6064 =head2 CREATING A RESET BUTTON
6068 reset() creates the "reset" button. Note that it restores the
6069 form to its value from the last time the script was called,
6070 NOT necessarily to the defaults.
6072 Note that this conflicts with the Perl reset() built-in. Use
6073 CORE::reset() to get the original reset function.
6075 =head2 CREATING A DEFAULT BUTTON
6077 print $query->defaults('button_label')
6079 defaults() creates a button that, when invoked, will cause the
6080 form to be completely reset to its defaults, wiping out all the
6081 changes the user ever made.
6083 =head2 CREATING A HIDDEN FIELD
6085 print $query->hidden(-name=>'hidden_name',
6086 -default=>['value1','value2'...]);
6090 print $query->hidden('hidden_name','value1','value2'...);
6092 hidden() produces a text field that can't be seen by the user. It
6093 is useful for passing state variable information from one invocation
6094 of the script to the next.
6098 =item B<Parameters:>
6102 The first argument is required and specifies the name of this
6107 The second argument is also required and specifies its value
6108 (-default). In the named parameter style of calling, you can provide
6109 a single value here or a reference to a whole list
6113 Fetch the value of a hidden field this way:
6115 $hidden_value = $query->param('hidden_name');
6117 Note, that just like all the other form elements, the value of a
6118 hidden field is "sticky". If you want to replace a hidden field with
6119 some other values after the script has been called once you'll have to
6122 $query->param('hidden_name','new','values','here');
6124 =head2 CREATING A CLICKABLE IMAGE BUTTON
6126 print $query->image_button(-name=>'button_name',
6127 -src=>'/source/URL',
6132 print $query->image_button('button_name','/source/URL','MIDDLE');
6134 image_button() produces a clickable image. When it's clicked on the
6135 position of the click is returned to your script as "button_name.x"
6136 and "button_name.y", where "button_name" is the name you've assigned
6139 JAVASCRIPTING: image_button() recognizes the B<-onClick>
6140 parameter. See checkbox_group() for further details.
6144 =item B<Parameters:>
6148 The first argument (-name) is required and specifies the name of this
6153 The second argument (-src) is also required and specifies the URL
6156 The third option (-align, optional) is an alignment type, and may be
6157 TOP, BOTTOM or MIDDLE
6161 Fetch the value of the button this way:
6162 $x = $query->param('button_name.x');
6163 $y = $query->param('button_name.y');
6165 =head2 CREATING A JAVASCRIPT ACTION BUTTON
6167 print $query->button(-name=>'button_name',
6168 -value=>'user visible label',
6169 -onClick=>"do_something()");
6173 print $query->button('button_name',"do_something()");
6175 button() produces a button that is compatible with Netscape 2.0's
6176 JavaScript. When it's pressed the fragment of JavaScript code
6177 pointed to by the B<-onClick> parameter will be executed. On
6178 non-Netscape browsers this form element will probably not even
6183 Netscape browsers versions 1.1 and higher, and all versions of
6184 Internet Explorer, support a so-called "cookie" designed to help
6185 maintain state within a browser session. CGI.pm has several methods
6186 that support cookies.
6188 A cookie is a name=value pair much like the named parameters in a CGI
6189 query string. CGI scripts create one or more cookies and send
6190 them to the browser in the HTTP header. The browser maintains a list
6191 of cookies that belong to a particular Web server, and returns them
6192 to the CGI script during subsequent interactions.
6194 In addition to the required name=value pair, each cookie has several
6195 optional attributes:
6199 =item 1. an expiration time
6201 This is a time/date string (in a special GMT format) that indicates
6202 when a cookie expires. The cookie will be saved and returned to your
6203 script until this expiration date is reached if the user exits
6204 the browser and restarts it. If an expiration date isn't specified, the cookie
6205 will remain active until the user quits the browser.
6209 This is a partial or complete domain name for which the cookie is
6210 valid. The browser will return the cookie to any host that matches
6211 the partial domain name. For example, if you specify a domain name
6212 of ".capricorn.com", then the browser will return the cookie to
6213 Web servers running on any of the machines "www.capricorn.com",
6214 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
6215 must contain at least two periods to prevent attempts to match
6216 on top level domains like ".edu". If no domain is specified, then
6217 the browser will only return the cookie to servers on the host the
6218 cookie originated from.
6222 If you provide a cookie path attribute, the browser will check it
6223 against your script's URL before returning the cookie. For example,
6224 if you specify the path "/cgi-bin", then the cookie will be returned
6225 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
6226 and "/cgi-bin/customer_service/complain.pl", but not to the script
6227 "/cgi-private/site_admin.pl". By default, path is set to "/", which
6228 causes the cookie to be sent to any CGI script on your site.
6230 =item 4. a "secure" flag
6232 If the "secure" attribute is set, the cookie will only be sent to your
6233 script if the CGI request is occurring on a secure channel, such as SSL.
6237 The interface to HTTP cookies is the B<cookie()> method:
6239 $cookie = $query->cookie(-name=>'sessionID',
6242 -path=>'/cgi-bin/database',
6243 -domain=>'.capricorn.org',
6245 print $query->header(-cookie=>$cookie);
6247 B<cookie()> creates a new cookie. Its parameters include:
6253 The name of the cookie (required). This can be any string at all.
6254 Although browsers limit their cookie names to non-whitespace
6255 alphanumeric characters, CGI.pm removes this restriction by escaping
6256 and unescaping cookies behind the scenes.
6260 The value of the cookie. This can be any scalar value,
6261 array reference, or even associative array reference. For example,
6262 you can store an entire associative array into a cookie this way:
6264 $cookie=$query->cookie(-name=>'family information',
6265 -value=>\%childrens_ages);
6269 The optional partial path for which this cookie will be valid, as described
6274 The optional partial domain for which this cookie will be valid, as described
6279 The optional expiration date for this cookie. The format is as described
6280 in the section on the B<header()> method:
6282 "+1h" one hour from now
6286 If set to true, this cookie will only be used within a secure
6291 The cookie created by cookie() must be incorporated into the HTTP
6292 header within the string returned by the header() method:
6294 print $query->header(-cookie=>$my_cookie);
6296 To create multiple cookies, give header() an array reference:
6298 $cookie1 = $query->cookie(-name=>'riddle_name',
6299 -value=>"The Sphynx's Question");
6300 $cookie2 = $query->cookie(-name=>'answers',
6302 print $query->header(-cookie=>[$cookie1,$cookie2]);
6304 To retrieve a cookie, request it by name by calling cookie() method
6305 without the B<-value> parameter:
6309 $riddle = $query->cookie('riddle_name');
6310 %answers = $query->cookie('answers');
6312 Cookies created with a single scalar value, such as the "riddle_name"
6313 cookie, will be returned in that form. Cookies with array and hash
6314 values can also be retrieved.
6316 The cookie and CGI namespaces are separate. If you have a parameter
6317 named 'answers' and a cookie named 'answers', the values retrieved by
6318 param() and cookie() are independent of each other. However, it's
6319 simple to turn a CGI parameter into a cookie, and vice-versa:
6321 # turn a CGI parameter into a cookie
6322 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
6324 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
6326 See the B<cookie.cgi> example script for some ideas on how to use
6327 cookies effectively.
6329 =head1 WORKING WITH FRAMES
6331 It's possible for CGI.pm scripts to write into several browser panels
6332 and windows using the HTML 4 frame mechanism. There are three
6333 techniques for defining new frames programmatically:
6337 =item 1. Create a <Frameset> document
6339 After writing out the HTTP header, instead of creating a standard
6340 HTML document using the start_html() call, create a <frameset>
6341 document that defines the frames on the page. Specify your script(s)
6342 (with appropriate parameters) as the SRC for each of the frames.
6344 There is no specific support for creating <frameset> sections
6345 in CGI.pm, but the HTML is very simple to write. See the frame
6346 documentation in Netscape's home pages for details
6348 http://home.netscape.com/assist/net_sites/frames.html
6350 =item 2. Specify the destination for the document in the HTTP header
6352 You may provide a B<-target> parameter to the header() method:
6354 print $q->header(-target=>'ResultsWindow');
6356 This will tell the browser to load the output of your script into the
6357 frame named "ResultsWindow". If a frame of that name doesn't already
6358 exist, the browser will pop up a new window and load your script's
6359 document into that. There are a number of magic names that you can
6360 use for targets. See the frame documents on Netscape's home pages for
6363 =item 3. Specify the destination for the document in the <form> tag
6365 You can specify the frame to load in the FORM tag itself. With
6366 CGI.pm it looks like this:
6368 print $q->start_form(-target=>'ResultsWindow');
6370 When your script is reinvoked by the form, its output will be loaded
6371 into the frame named "ResultsWindow". If one doesn't already exist
6372 a new window will be created.
6376 The script "frameset.cgi" in the examples directory shows one way to
6377 create pages in which the fill-out form and the response live in
6378 side-by-side frames.
6380 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
6382 CGI.pm has limited support for HTML3's cascading style sheets (css).
6383 To incorporate a stylesheet into your document, pass the
6384 start_html() method a B<-style> parameter. The value of this
6385 parameter may be a scalar, in which case it is incorporated directly
6386 into a <style> section, or it may be a hash reference. In the latter
6387 case you should provide the hash with one or more of B<-src> or
6388 B<-code>. B<-src> points to a URL where an externally-defined
6389 stylesheet can be found. B<-code> points to a scalar value to be
6390 incorporated into a <style> section. Style definitions in B<-code>
6391 override similarly-named ones in B<-src>, hence the name "cascading."
6393 You may also specify the type of the stylesheet by adding the optional
6394 B<-type> parameter to the hash pointed to by B<-style>. If not
6395 specified, the style defaults to 'text/css'.
6397 To refer to a style within the body of your document, add the
6398 B<-class> parameter to any HTML element:
6400 print h1({-class=>'Fancy'},'Welcome to the Party');
6402 Or define styles on the fly with the B<-style> parameter:
6404 print h1({-style=>'Color: red;'},'Welcome to Hell');
6406 You may also use the new B<span()> element to apply a style to a
6409 print span({-style=>'Color: red;'},
6410 h1('Welcome to Hell'),
6411 "Where did that handbasket get to?"
6414 Note that you must import the ":html3" definitions to have the
6415 B<span()> method available. Here's a quick and dirty example of using
6416 CSS's. See the CSS specification at
6417 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
6419 use CGI qw/:standard :html3/;
6421 #here's a stylesheet incorporated directly into the page
6431 font-family: sans-serif;
6437 print start_html( -title=>'CGI with Style',
6438 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
6441 print h1('CGI with Style'),
6443 "Better read the cascading style sheet spec before playing with this!"),
6444 span({-style=>'color: magenta'},
6445 "Look Mom, no hands!",
6451 Pass an array reference to B<-style> in order to incorporate multiple
6452 stylesheets into your document.
6454 Should you wish to incorporate a verbatim stylesheet that includes
6455 arbitrary formatting in the header, you may pass a -verbatim tag to
6456 the -style hash, as follows:
6458 print $q->start_html (-STYLE => {-verbatim => '@import
6459 url("/server-common/css/'.$cssFile.'");',
6460 -src => '/server-common/css/core.css'});
6464 This will generate an HTML header that contains this:
6466 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
6467 <style type="text/css">
6468 @import url("/server-common/css/main.css");
6471 Any additional arguments passed in the -style value will be
6472 incorporated into the <link> tag. For example:
6474 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
6479 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
6480 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
6484 To make more complicated <link> tags, use the Link() function
6485 and pass it to start_html() in the -head argument, as in:
6487 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
6488 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
6489 print start_html({-head=>\@h})
6493 If you are running the script from the command line or in the perl
6494 debugger, you can pass the script a list of keywords or
6495 parameter=value pairs on the command line or from standard input (you
6496 don't have to worry about tricking your script into reading from
6497 environment variables). You can pass keywords like this:
6499 your_script.pl keyword1 keyword2 keyword3
6503 your_script.pl keyword1+keyword2+keyword3
6507 your_script.pl name1=value1 name2=value2
6511 your_script.pl name1=value1&name2=value2
6513 To turn off this feature, use the -no_debug pragma.
6515 To test the POST method, you may enable full debugging with the -debug
6516 pragma. This will allow you to feed newline-delimited name=value
6517 pairs to the script on standard input.
6519 When debugging, you can use quotes and backslashes to escape
6520 characters in the familiar shell manner, letting you place
6521 spaces and other funny characters in your parameter=value
6524 your_script.pl "name1='I am a long value'" "name2=two\ words"
6526 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
6528 The Dump() method produces a string consisting of all the query's
6529 name/value pairs formatted nicely as a nested list. This is useful
6530 for debugging purposes:
6535 Produces something that looks like:
6549 As a shortcut, you can interpolate the entire CGI object into a string
6550 and it will be replaced with the a nice HTML dump shown above:
6553 print "<h2>Current Values</h2> $query\n";
6555 =head1 FETCHING ENVIRONMENT VARIABLES
6557 Some of the more useful environment variables can be fetched
6558 through this interface. The methods are as follows:
6564 Return a list of MIME types that the remote browser accepts. If you
6565 give this method a single argument corresponding to a MIME type, as in
6566 $query->Accept('text/html'), it will return a floating point value
6567 corresponding to the browser's preference for this type from 0.0
6568 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
6569 list are handled correctly.
6571 Note that the capitalization changed between version 2.43 and 2.44 in
6572 order to avoid conflict with Perl's accept() function.
6574 =item B<raw_cookie()>
6576 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
6577 Netscape browsers version 1.1 and higher, and all versions of Internet
6578 Explorer. Cookies have a special format, and this method call just
6579 returns the raw form (?cookie dough). See cookie() for ways of
6580 setting and retrieving cooked cookies.
6582 Called with no parameters, raw_cookie() returns the packed cookie
6583 structure. You can separate it into individual cookies by splitting
6584 on the character sequence "; ". Called with the name of a cookie,
6585 retrieves the B<unescaped> form of the cookie. You can use the
6586 regular cookie() method to get the names, or use the raw_fetch()
6587 method from the CGI::Cookie module.
6589 =item B<user_agent()>
6591 Returns the HTTP_USER_AGENT variable. If you give
6592 this method a single argument, it will attempt to
6593 pattern match on it, allowing you to do something
6594 like $query->user_agent(netscape);
6596 =item B<path_info()>
6598 Returns additional path information from the script URL.
6599 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
6600 $query->path_info() returning "/additional/stuff".
6602 NOTE: The Microsoft Internet Information Server
6603 is broken with respect to additional path information. If
6604 you use the Perl DLL library, the IIS server will attempt to
6605 execute the additional path information as a Perl script.
6606 If you use the ordinary file associations mapping, the
6607 path information will be present in the environment,
6608 but incorrect. The best thing to do is to avoid using additional
6609 path information in CGI scripts destined for use with IIS.
6611 =item B<path_translated()>
6613 As per path_info() but returns the additional
6614 path information translated into a physical path, e.g.
6615 "/usr/local/etc/httpd/htdocs/additional/stuff".
6617 The Microsoft IIS is broken with respect to the translated
6620 =item B<remote_host()>
6622 Returns either the remote host name or IP address.
6623 if the former is unavailable.
6625 =item B<script_name()>
6626 Return the script name as a partial URL, for self-refering
6631 Return the URL of the page the browser was viewing
6632 prior to fetching your script. Not available for all
6635 =item B<auth_type ()>
6637 Return the authorization/verification method in use for this
6640 =item B<server_name ()>
6642 Returns the name of the server, usually the machine's host
6645 =item B<virtual_host ()>
6647 When using virtual hosts, returns the name of the host that
6648 the browser attempted to contact
6650 =item B<server_port ()>
6652 Return the port that the server is listening on.
6654 =item B<server_software ()>
6656 Returns the server software and version number.
6658 =item B<remote_user ()>
6660 Return the authorization/verification name used for user
6661 verification, if this script is protected.
6663 =item B<user_name ()>
6665 Attempt to obtain the remote user's name, using a variety of different
6666 techniques. This only works with older browsers such as Mosaic.
6667 Newer browsers do not report the user name for privacy reasons!
6669 =item B<request_method()>
6671 Returns the method used to access your script, usually
6672 one of 'POST', 'GET' or 'HEAD'.
6674 =item B<content_type()>
6676 Returns the content_type of data submitted in a POST, generally
6677 multipart/form-data or application/x-www-form-urlencoded
6681 Called with no arguments returns the list of HTTP environment
6682 variables, including such things as HTTP_USER_AGENT,
6683 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6684 like-named HTTP header fields in the request. Called with the name of
6685 an HTTP header field, returns its value. Capitalization and the use
6686 of hyphens versus underscores are not significant.
6688 For example, all three of these examples are equivalent:
6690 $requested_language = $q->http('Accept-language');
6691 $requested_language = $q->http('Accept_language');
6692 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6696 The same as I<http()>, but operates on the HTTPS environment variables
6697 present when the SSL protocol is in effect. Can be used to determine
6698 whether SSL is turned on.
6702 =head1 USING NPH SCRIPTS
6704 NPH, or "no-parsed-header", scripts bypass the server completely by
6705 sending the complete HTTP header directly to the browser. This has
6706 slight performance benefits, but is of most use for taking advantage
6707 of HTTP extensions that are not directly supported by your server,
6708 such as server push and PICS headers.
6710 Servers use a variety of conventions for designating CGI scripts as
6711 NPH. Many Unix servers look at the beginning of the script's name for
6712 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
6713 Internet Information Server, in contrast, try to decide whether a
6714 program is an NPH script by examining the first line of script output.
6717 CGI.pm supports NPH scripts with a special NPH mode. When in this
6718 mode, CGI.pm will output the necessary extra header information when
6719 the header() and redirect() methods are
6722 The Microsoft Internet Information Server requires NPH mode. As of
6723 version 2.30, CGI.pm will automatically detect when the script is
6724 running under IIS and put itself into this mode. You do not need to
6725 do this manually, although it won't hurt anything if you do. However,
6726 note that if you have applied Service Pack 6, much of the
6727 functionality of NPH scripts, including the ability to redirect while
6728 setting a cookie, b<do not work at all> on IIS without a special patch
6730 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
6731 Non-Parsed Headers Stripped From CGI Applications That Have nph-
6736 =item In the B<use> statement
6738 Simply add the "-nph" pragmato the list of symbols to be imported into
6741 use CGI qw(:standard -nph)
6743 =item By calling the B<nph()> method:
6745 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
6749 =item By using B<-nph> parameters
6751 in the B<header()> and B<redirect()> statements:
6753 print $q->header(-nph=>1);
6759 CGI.pm provides four simple functions for producing multipart
6760 documents of the type needed to implement server push. These
6761 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
6762 import these into your namespace, you must import the ":push" set.
6763 You are also advised to put the script into NPH mode and to set $| to
6764 1 to avoid buffering problems.
6766 Here is a simple script that demonstrates server push:
6768 #!/usr/local/bin/perl
6769 use CGI qw/:push -nph/;
6771 print multipart_init(-boundary=>'----here we go!');
6773 print multipart_start(-type=>'text/plain'),
6774 "The current time is ",scalar(localtime),"\n";
6776 print multipart_end;
6778 print multipart_final;
6783 This script initializes server push by calling B<multipart_init()>.
6784 It then enters a loop in which it begins a new multipart section by
6785 calling B<multipart_start()>, prints the current local time,
6786 and ends a multipart section with B<multipart_end()>. It then sleeps
6787 a second, and begins again. On the final iteration, it ends the
6788 multipart section with B<multipart_final()> rather than with
6793 =item multipart_init()
6795 multipart_init(-boundary=>$boundary);
6797 Initialize the multipart system. The -boundary argument specifies
6798 what MIME boundary string to use to separate parts of the document.
6799 If not provided, CGI.pm chooses a reasonable boundary for you.
6801 =item multipart_start()
6803 multipart_start(-type=>$type)
6805 Start a new part of the multipart document using the specified MIME
6806 type. If not specified, text/html is assumed.
6808 =item multipart_end()
6812 End a part. You must remember to call multipart_end() once for each
6813 multipart_start(), except at the end of the last part of the multipart
6814 document when multipart_final() should be called instead of multipart_end().
6816 =item multipart_final()
6820 End all parts. You should call multipart_final() rather than
6821 multipart_end() at the end of the last part of the multipart document.
6825 Users interested in server push applications should also have a look
6826 at the CGI::Push module.
6828 Only Netscape Navigator supports server push. Internet Explorer
6831 =head1 Avoiding Denial of Service Attacks
6833 A potential problem with CGI.pm is that, by default, it attempts to
6834 process form POSTings no matter how large they are. A wily hacker
6835 could attack your site by sending a CGI script a huge POST of many
6836 megabytes. CGI.pm will attempt to read the entire POST into a
6837 variable, growing hugely in size until it runs out of memory. While
6838 the script attempts to allocate the memory the system may slow down
6839 dramatically. This is a form of denial of service attack.
6841 Another possible attack is for the remote user to force CGI.pm to
6842 accept a huge file upload. CGI.pm will accept the upload and store it
6843 in a temporary directory even if your script doesn't expect to receive
6844 an uploaded file. CGI.pm will delete the file automatically when it
6845 terminates, but in the meantime the remote user may have filled up the
6846 server's disk space, causing problems for other programs.
6848 The best way to avoid denial of service attacks is to limit the amount
6849 of memory, CPU time and disk space that CGI scripts can use. Some Web
6850 servers come with built-in facilities to accomplish this. In other
6851 cases, you can use the shell I<limit> or I<ulimit>
6852 commands to put ceilings on CGI resource usage.
6855 CGI.pm also has some simple built-in protections against denial of
6856 service attacks, but you must activate them before you can use them.
6857 These take the form of two global variables in the CGI name space:
6861 =item B<$CGI::POST_MAX>
6863 If set to a non-negative integer, this variable puts a ceiling
6864 on the size of POSTings, in bytes. If CGI.pm detects a POST
6865 that is greater than the ceiling, it will immediately exit with an error
6866 message. This value will affect both ordinary POSTs and
6867 multipart POSTs, meaning that it limits the maximum size of file
6868 uploads as well. You should set this to a reasonably high
6869 value, such as 1 megabyte.
6871 =item B<$CGI::DISABLE_UPLOADS>
6873 If set to a non-zero value, this will disable file uploads
6874 completely. Other fill-out form values will work as usual.
6878 You can use these variables in either of two ways.
6882 =item B<1. On a script-by-script basis>
6884 Set the variable at the top of the script, right after the "use" statement:
6886 use CGI qw/:standard/;
6887 use CGI::Carp 'fatalsToBrowser';
6888 $CGI::POST_MAX=1024 * 100; # max 100K posts
6889 $CGI::DISABLE_UPLOADS = 1; # no uploads
6891 =item B<2. Globally for all scripts>
6893 Open up CGI.pm, find the definitions for $POST_MAX and
6894 $DISABLE_UPLOADS, and set them to the desired values. You'll
6895 find them towards the top of the file in a subroutine named
6896 initialize_globals().
6900 An attempt to send a POST larger than $POST_MAX bytes will cause
6901 I<param()> to return an empty CGI parameter list. You can test for
6902 this event by checking I<cgi_error()>, either after you create the CGI
6903 object or, if you are using the function-oriented interface, call
6904 <param()> for the first time. If the POST was intercepted, then
6905 cgi_error() will return the message "413 POST too large".
6907 This error message is actually defined by the HTTP protocol, and is
6908 designed to be returned to the browser as the CGI script's status
6911 $uploaded_file = param('upload');
6912 if (!$uploaded_file && cgi_error()) {
6913 print header(-status=>cgi_error());
6917 However it isn't clear that any browser currently knows what to do
6918 with this status code. It might be better just to create an
6919 HTML page that warns the user of the problem.
6921 =head1 COMPATIBILITY WITH CGI-LIB.PL
6923 To make it easier to port existing programs that use cgi-lib.pl the
6924 compatibility routine "ReadParse" is provided. Porting is simple:
6927 require "cgi-lib.pl";
6929 print "The value of the antique is $in{antique}.\n";
6934 print "The value of the antique is $in{antique}.\n";
6936 CGI.pm's ReadParse() routine creates a tied variable named %in,
6937 which can be accessed to obtain the query variables. Like
6938 ReadParse, you can also provide your own variable. Infrequently
6939 used features of ReadParse, such as the creation of @in and $in
6940 variables, are not supported.
6942 Once you use ReadParse, you can retrieve the query object itself
6946 print $q->textfield(-name=>'wow',
6947 -value=>'does this really work?');
6949 This allows you to start using the more interesting features
6950 of CGI.pm without rewriting your old scripts from scratch.
6952 =head1 AUTHOR INFORMATION
6954 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
6956 This library is free software; you can redistribute it and/or modify
6957 it under the same terms as Perl itself.
6959 Address bug reports and comments to: lstein@cshl.org. When sending
6960 bug reports, please provide the version of CGI.pm, the version of
6961 Perl, the name and version of your Web server, and the name and
6962 version of the operating system you are using. If the problem is even
6963 remotely browser dependent, please provide information about the
6964 affected browers as well.
6968 Thanks very much to:
6972 =item Matt Heffron (heffron@falstaff.css.beckman.com)
6974 =item James Taylor (james.taylor@srs.gov)
6976 =item Scott Anguish <sanguish@digifix.com>
6978 =item Mike Jewell (mlj3u@virginia.edu)
6980 =item Timothy Shimmin (tes@kbs.citri.edu.au)
6982 =item Joergen Haegg (jh@axis.se)
6984 =item Laurent Delfosse (delfosse@delfosse.com)
6986 =item Richard Resnick (applepi1@aol.com)
6988 =item Craig Bishop (csb@barwonwater.vic.gov.au)
6990 =item Tony Curtis (tc@vcpc.univie.ac.at)
6992 =item Tim Bunce (Tim.Bunce@ig.co.uk)
6994 =item Tom Christiansen (tchrist@convex.com)
6996 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
6998 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
7000 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
7002 =item Stephen Dahmen (joyfire@inxpress.net)
7004 =item Ed Jordan (ed@fidalgo.net)
7006 =item David Alan Pisoni (david@cnation.com)
7008 =item Doug MacEachern (dougm@opengroup.org)
7010 =item Robin Houston (robin@oneworld.org)
7012 =item ...and many many more...
7014 for suggestions and bug fixes.
7018 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
7021 #!/usr/local/bin/perl
7027 print $query->header;
7028 print $query->start_html("Example CGI.pm Form");
7029 print "<h1> Example CGI.pm Form</h1>\n";
7030 &print_prompt($query);
7033 print $query->end_html;
7038 print $query->start_form;
7039 print "<em>What's your name?</em><br>";
7040 print $query->textfield('name');
7041 print $query->checkbox('Not my real name');
7043 print "<p><em>Where can you find English Sparrows?</em><br>";
7044 print $query->checkbox_group(
7045 -name=>'Sparrow locations',
7046 -values=>[England,France,Spain,Asia,Hoboken],
7048 -defaults=>[England,Asia]);
7050 print "<p><em>How far can they fly?</em><br>",
7051 $query->radio_group(
7053 -values=>['10 ft','1 mile','10 miles','real far'],
7054 -default=>'1 mile');
7056 print "<p><em>What's your favorite color?</em> ";
7057 print $query->popup_menu(-name=>'Color',
7058 -values=>['black','brown','red','yellow'],
7061 print $query->hidden('Reference','Monty Python and the Holy Grail');
7063 print "<p><em>What have you got there?</em><br>";
7064 print $query->scrolling_list(
7065 -name=>'possessions',
7066 -values=>['A Coconut','A Grail','An Icon',
7067 'A Sword','A Ticket'],
7071 print "<p><em>Any parting comments?</em><br>";
7072 print $query->textarea(-name=>'Comments',
7076 print "<p>",$query->reset;
7077 print $query->submit('Action','Shout');
7078 print $query->submit('Action','Scream');
7079 print $query->endform;
7087 print "<h2>Here are the current settings in this form</h2>";
7089 foreach $key ($query->param) {
7090 print "<strong>$key</strong> -> ";
7091 @values = $query->param($key);
7092 print join(", ",@values),"<br>\n";
7099 <address>Lincoln D. Stein</address><br>
7100 <a href="/">Home Page</a>
7110 L<CGI::Carp>, L<CGI::Fast>, L<CGI::Pretty>