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.151 2004/01/13 16:28:35 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 ebcdic2ascii ascii2ebcdic);
29 #use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN',
30 # 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];
32 use constant XHTML_DTD => ['-//W3C//DTD XHTML 1.0 Transitional//EN',
33 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'];
37 $TAINTED = substr("$0$^X",0,0);
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::Response;
185 require Apache::RequestRec;
186 require Apache::RequestUtil;
195 # Turn on special checking for ActiveState's PerlEx
196 $PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;
198 # Define the CRLF sequence. I can't use a simple "\r\n" because the meaning
199 # of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF
200 # and sometimes CR). The most popular VMS web server
201 # doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't
202 # use ASCII, so \015\012 means something different. I find this all
204 $EBCDIC = "\t" ne "\011";
213 if ($needs_binmode) {
214 $CGI::DefaultClass->binmode(\*main::STDOUT);
215 $CGI::DefaultClass->binmode(\*main::STDIN);
216 $CGI::DefaultClass->binmode(\*main::STDERR);
220 ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em
221 tt u i b blockquote pre img a address cite samp dfn html head
222 base body Link nextid title meta kbd start_html end_html
223 input Select option comment charset escapeHTML/],
224 ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param
225 embed basefont style span layer ilayer font frameset frame script small big Area Map/],
226 ':html4'=>[qw/abbr acronym bdo col colgroup del fieldset iframe
227 ins label legend noframes noscript object optgroup Q
229 ':netscape'=>[qw/blink fontsize center/],
230 ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group
231 submit reset defaults radio_group popup_menu button autoEscape
232 scrolling_list image_button start_form end_form startform endform
233 start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/],
234 ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump
235 raw_cookie request_method query_string Accept user_agent remote_host content_type
236 remote_addr referer server_name server_software server_port server_protocol virtual_port
237 virtual_host remote_ident auth_type http append
238 save_parameters restore_parameters param_fetch
239 remote_user user_name header redirect import_names put
240 Delete Delete_all url_param cgi_error/],
241 ':ssl' => [qw/https/],
242 ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/],
243 ':html' => [qw/:html2 :html3 :html4 :netscape/],
244 ':standard' => [qw/:html2 :html3 :html4 :form :cgi/],
245 ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/],
246 ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal :html4/]
249 # to import symbols into caller
253 # This causes modules to clash.
257 $self->_setup_symbols(@_);
258 my ($callpack, $callfile, $callline) = caller;
260 # To allow overriding, search through the packages
261 # Till we find one in which the correct subroutine is defined.
262 my @packages = ($self,@{"$self\:\:ISA"});
263 foreach $sym (keys %EXPORT) {
265 my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass;
266 foreach $pck (@packages) {
267 if (defined(&{"$pck\:\:$sym"})) {
272 *{"${callpack}::$sym"} = \&{"$def\:\:$sym"};
278 $pack->_setup_symbols('-compile',@_);
283 return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/;
285 return ($tag) unless $EXPORT_TAGS{$tag};
286 foreach (@{$EXPORT_TAGS{$tag}}) {
287 push(@r,&expand_tags($_));
293 # The new routine. This will check the current environment
294 # for an existing query string, and initialize itself, if so.
297 my($class,@initializer) = @_;
300 bless $self,ref $class || $class || $DefaultClass;
301 if (ref($initializer[0])
302 && (UNIVERSAL::isa($initializer[0],'Apache')
304 UNIVERSAL::isa($initializer[0],'Apache::RequestRec')
306 $self->r(shift @initializer);
308 if (ref($initializer[0])
309 && (UNIVERSAL::isa($initializer[0],'CODE'))) {
310 $self->upload_hook(shift @initializer, shift @initializer);
313 $self->r(Apache->request) unless $self->r;
315 if ($MOD_PERL == 1) {
316 $r->register_cleanup(\&CGI::_reset_globals);
319 # XXX: once we have the new API
320 # will do a real PerlOptions -SetupEnv check
321 $r->subprocess_env unless exists $ENV{REQUEST_METHOD};
322 $r->pool->cleanup_register(\&CGI::_reset_globals);
326 $self->_reset_globals if $PERLEX;
327 $self->init(@initializer);
331 # We provide a DESTROY method so that we can ensure that
332 # temporary files are closed (via Fh->DESTROY) before they
333 # are unlinked (via CGITempFile->DESTROY) because it is not
334 # possible to unlink an open file on Win32. We explicitly
335 # call DESTROY on each, rather than just undefing them and
336 # letting Perl DESTROY them by garbage collection, in case the
337 # user is still holding any reference to them as well.
340 foreach my $href (values %{$self->{'.tmpfiles'}}) {
341 $href->{hndl}->DESTROY if defined $href->{hndl};
342 $href->{name}->DESTROY if defined $href->{name};
348 my $r = $self->{'.r'};
349 $self->{'.r'} = shift if @_;
354 my ($self,$hook,$data) = self_or_default(@_);
355 $self->{'.upload_hook'} = $hook;
356 $self->{'.upload_data'} = $data;
360 # Returns the value(s)of a named parameter.
361 # If invoked in a list context, returns the
362 # entire list. Otherwise returns the first
363 # member of the list.
364 # If name is not provided, return a list of all
365 # the known parameters names available.
366 # If more than one argument is provided, the
367 # second and subsequent arguments are used to
368 # set the value of the parameter.
371 my($self,@p) = self_or_default(@_);
372 return $self->all_parameters unless @p;
373 my($name,$value,@other);
375 # For compatibility between old calling style and use_named_parameters() style,
376 # we have to special case for a single parameter present.
378 ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p);
381 if (substr($p[0],0,1) eq '-') {
382 @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : ();
384 foreach ($value,@other) {
385 push(@values,$_) if defined($_);
388 # If values is provided, then we set it.
390 $self->add_parameter($name);
391 $self->{$name}=[@values];
397 return unless defined($name) && $self->{$name};
398 return wantarray ? @{$self->{$name}} : $self->{$name}->[0];
401 sub self_or_default {
402 return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI');
403 unless (defined($_[0]) &&
404 (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case
406 $Q = $CGI::DefaultClass->new unless defined($Q);
409 return wantarray ? @_ : $Q;
413 local $^W=0; # prevent a warning
414 if (defined($_[0]) &&
415 (substr(ref($_[0]),0,3) eq 'CGI'
416 || UNIVERSAL::isa($_[0],'CGI'))) {
419 return ($DefaultClass,@_);
423 ########################################
424 # THESE METHODS ARE MORE OR LESS PRIVATE
425 # GO TO THE __DATA__ SECTION TO SEE MORE
427 ########################################
429 # Initialize the query object from the environment.
430 # If a parameter list is found, this object will be set
431 # to an associative array in which parameter names are keys
432 # and the values are stored as lists
433 # If a keyword list is found, this method creates a bogus
434 # parameter list with the single parameter 'keywords'.
438 my($query_string,$meth,$content_length,$fh,@lines) = ('','','','');
440 my $initializer = shift; # for backward compatibility
443 # set autoescaping on by default
444 $self->{'escape'} = 1;
446 # if we get called more than once, we want to initialize
447 # ourselves from the original query (which may be gone
448 # if it was read from STDIN originally.)
449 if (defined(@QUERY_PARAM) && !defined($initializer)) {
450 foreach (@QUERY_PARAM) {
451 $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_});
453 $self->charset($QUERY_CHARSET);
454 $self->{'.fieldnames'} = {%QUERY_FIELDNAMES};
458 $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'});
459 $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0;
461 $fh = to_filehandle($initializer) if $initializer;
463 # set charset to the safe ISO-8859-1
464 $self->charset('ISO-8859-1');
468 # avoid unreasonably large postings
469 if (($POST_MAX > 0) && ($content_length > $POST_MAX)) {
470 # quietly read and discard the post
472 my $max = $content_length;
474 (my $bytes = $MOD_PERL
475 ? $self->r->read($buffer,$max < 10000 ? $max : 10000)
476 : read(STDIN,$buffer,$max < 10000 ? $max : 10000)
478 $self->cgi_error("413 Request entity too large");
483 # Process multipart postings, but only if the initializer is
486 && defined($ENV{'CONTENT_TYPE'})
487 && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data|
488 && !defined($initializer)
490 my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
491 $self->read_multipart($boundary,$content_length);
495 # If initializer is defined, then read parameters
497 if (defined($initializer)) {
498 if (UNIVERSAL::isa($initializer,'CGI')) {
499 $query_string = $initializer->query_string;
502 if (ref($initializer) && ref($initializer) eq 'HASH') {
503 foreach (keys %$initializer) {
504 $self->param('-name'=>$_,'-value'=>$initializer->{$_});
509 if (defined($fh) && ($fh ne '')) {
515 # massage back into standard format
516 if ("@lines" =~ /=/) {
517 $query_string=join("&",@lines);
519 $query_string=join("+",@lines);
524 if (defined($fh) && ($fh ne '')) {
530 # massage back into standard format
531 if ("@lines" =~ /=/) {
532 $query_string=join("&",@lines);
534 $query_string=join("+",@lines);
539 # last chance -- treat it as a string
540 $initializer = $$initializer if ref($initializer) eq 'SCALAR';
541 $query_string = $initializer;
546 # If method is GET or HEAD, fetch the query from
548 if ($meth=~/^(GET|HEAD)$/) {
550 $query_string = $self->r->args;
552 $query_string = $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
553 $query_string ||= $ENV{'REDIRECT_QUERY_STRING'} if defined $ENV{'REDIRECT_QUERY_STRING'};
558 if ($meth eq 'POST') {
559 $self->read_from_client(\$query_string,$content_length,0)
560 if $content_length > 0;
561 # Some people want to have their cake and eat it too!
562 # Uncomment this line to have the contents of the query string
563 # APPENDED to the POST data.
564 # $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
568 # If $meth is not of GET, POST or HEAD, assume we're being debugged offline.
569 # Check the command line and then the standard input for data.
570 # We use the shellwords package in order to behave the way that
571 # UN*X programmers expect.
574 my $cmdline_ret = read_from_cmdline();
575 $query_string = $cmdline_ret->{'query_string'};
576 if (defined($cmdline_ret->{'subpath'}))
578 $self->path_info($cmdline_ret->{'subpath'});
583 # YL: Begin Change for XML handler 10/19/2001
585 && defined($ENV{'CONTENT_TYPE'})
586 && $ENV{'CONTENT_TYPE'} !~ m|^application/x-www-form-urlencoded|
587 && $ENV{'CONTENT_TYPE'} !~ m|^multipart/form-data| ) {
588 my($param) = 'POSTDATA' ;
589 $self->add_parameter($param) ;
590 push (@{$self->{$param}},$query_string);
591 undef $query_string ;
593 # YL: End Change for XML handler 10/19/2001
595 # We now have the query string in hand. We do slightly
596 # different things for keyword lists and parameter lists.
597 if (defined $query_string && length $query_string) {
598 if ($query_string =~ /[&=;]/) {
599 $self->parse_params($query_string);
601 $self->add_parameter('keywords');
602 $self->{'keywords'} = [$self->parse_keywordlist($query_string)];
606 # Special case. Erase everything if there is a field named
608 if ($self->param('.defaults')) {
612 # Associative array containing our defined fieldnames
613 $self->{'.fieldnames'} = {};
614 foreach ($self->param('.cgifields')) {
615 $self->{'.fieldnames'}->{$_}++;
618 # Clear out our default submission button flag if present
619 $self->delete('.submit');
620 $self->delete('.cgifields');
622 $self->save_request unless defined $initializer;
625 # FUNCTIONS TO OVERRIDE:
626 # Turn a string into a filehandle
629 return undef unless $thingy;
630 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
631 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
634 while (my $package = caller($caller++)) {
635 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
636 return $tmp if defined(fileno($tmp));
642 # send output to the browser
644 my($self,@p) = self_or_default(@_);
648 # print to standard output (for overriding in mod_perl)
654 # get/set last cgi_error
656 my ($self,$err) = self_or_default(@_);
657 $self->{'.cgi_error'} = $err if defined $err;
658 return $self->{'.cgi_error'};
663 # We're going to play with the package globals now so that if we get called
664 # again, we initialize ourselves in exactly the same way. This allows
665 # us to have several of these objects.
666 @QUERY_PARAM = $self->param; # save list of parameters
667 foreach (@QUERY_PARAM) {
668 next unless defined $_;
669 $QUERY_PARAM{$_}=$self->{$_};
671 $QUERY_CHARSET = $self->charset;
672 %QUERY_FIELDNAMES = %{$self->{'.fieldnames'}};
676 my($self,$tosplit) = @_;
677 my(@pairs) = split(/[&;]/,$tosplit);
680 ($param,$value) = split('=',$_,2);
681 next unless defined $param;
682 next if $NO_UNDEF_PARAMS and not defined $value;
683 $value = '' unless defined $value;
684 $param = unescape($param);
685 $value = unescape($value);
686 $self->add_parameter($param);
687 push (@{$self->{$param}},$value);
693 return unless defined $param;
694 push (@{$self->{'.parameters'}},$param)
695 unless defined($self->{$param});
700 return () unless defined($self) && $self->{'.parameters'};
701 return () unless @{$self->{'.parameters'}};
702 return @{$self->{'.parameters'}};
705 # put a filehandle into binary mode (DOS)
707 return unless defined($_[1]) && defined fileno($_[1]);
708 CORE::binmode($_[1]);
712 my ($self,$tagname) = @_;
715 my (\$q,\$a,\@rest) = self_or_default(\@_);
717 if (ref(\$a) && ref(\$a) eq 'HASH') {
718 my(\@attr) = make_attributes(\$a,\$q->{'escape'});
719 \$attr = " \@attr" if \@attr;
721 unshift \@rest,\$a if defined \$a;
724 if ($tagname=~/start_(\w+)/i) {
725 $func .= qq! return "<\L$1\E\$attr>";} !;
726 } elsif ($tagname=~/end_(\w+)/i) {
727 $func .= qq! return "<\L/$1\E>"; } !;
730 return \$XHTML ? "\L<$tagname\E\$attr />" : "\L<$tagname\E\$attr>" unless \@rest;
731 my(\$tag,\$untag) = ("\L<$tagname\E\$attr>","\L</$tagname>\E");
732 my \@result = map { "\$tag\$_\$untag" }
733 (ref(\$rest[0]) eq 'ARRAY') ? \@{\$rest[0]} : "\@rest";
741 print STDERR "CGI::AUTOLOAD for $AUTOLOAD\n" if $CGI::AUTOLOAD_DEBUG;
742 my $func = &_compile;
747 my($func) = $AUTOLOAD;
748 my($pack,$func_name);
750 local($1,$2); # this fixes an obscure variable suicide problem.
751 $func=~/(.+)::([^:]+)$/;
752 ($pack,$func_name) = ($1,$2);
753 $pack=~s/::SUPER$//; # fix another obscure problem
754 $pack = ${"$pack\:\:AutoloadClass"} || $CGI::DefaultClass
755 unless defined(${"$pack\:\:AUTOLOADED_ROUTINES"});
757 my($sub) = \%{"$pack\:\:SUBS"};
759 my($auto) = \${"$pack\:\:AUTOLOADED_ROUTINES"};
760 eval "package $pack; $$auto";
761 croak("$AUTOLOAD: $@") if $@;
762 $$auto = ''; # Free the unneeded storage (but don't undef it!!!)
764 my($code) = $sub->{$func_name};
766 $code = "sub $AUTOLOAD { }" if (!$code and $func_name eq 'DESTROY');
768 (my $base = $func_name) =~ s/^(start_|end_)//i;
769 if ($EXPORT{':any'} ||
772 (%EXPORT_OK || grep(++$EXPORT_OK{$_},&expand_tags(':html')))
773 && $EXPORT_OK{$base}) {
774 $code = $CGI::DefaultClass->_make_tag_func($func_name);
777 croak("Undefined subroutine $AUTOLOAD\n") unless $code;
778 eval "package $pack; $code";
781 croak("$AUTOLOAD: $@");
784 CORE::delete($sub->{$func_name}); #free storage
785 return "$pack\:\:$func_name";
791 return '' unless $value;
792 return $XHTML ? qq( selected="selected") : qq( selected);
798 return '' unless $value;
799 return $XHTML ? qq( checked="checked") : qq( checked);
802 sub _reset_globals { initialize_globals(); }
808 # to avoid reexporting unwanted variables
812 $HEADERS_ONCE++, next if /^[:-]unique_headers$/;
813 $NPH++, next if /^[:-]nph$/;
814 $NOSTICKY++, next if /^[:-]nosticky$/;
815 $DEBUG=0, next if /^[:-]no_?[Dd]ebug$/;
816 $DEBUG=2, next if /^[:-][Dd]ebug$/;
817 $USE_PARAM_SEMICOLONS++, next if /^[:-]newstyle_urls$/;
818 $XHTML++, next if /^[:-]xhtml$/;
819 $XHTML=0, next if /^[:-]no_?xhtml$/;
820 $USE_PARAM_SEMICOLONS=0, next if /^[:-]oldstyle_urls$/;
821 $PRIVATE_TEMPFILES++, next if /^[:-]private_tempfiles$/;
822 $CLOSE_UPLOAD_FILES++, next if /^[:-]close_upload_files$/;
823 $EXPORT{$_}++, next if /^[:-]any$/;
824 $compile++, next if /^[:-]compile$/;
825 $NO_UNDEF_PARAMS++, next if /^[:-]no_undef_params$/;
827 # This is probably extremely evil code -- to be deleted some day.
828 if (/^[-]autoload$/) {
829 my($pkg) = caller(1);
830 *{"${pkg}::AUTOLOAD"} = sub {
831 my($routine) = $AUTOLOAD;
832 $routine =~ s/^.*::/CGI::/;
838 foreach (&expand_tags($_)) {
839 tr/a-zA-Z0-9_//cd; # don't allow weird function names
843 _compile_all(keys %EXPORT) if $compile;
848 my ($self,$charset) = self_or_default(@_);
849 $self->{'.charset'} = $charset if defined $charset;
853 ###############################################################################
854 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
855 ###############################################################################
856 $AUTOLOADED_ROUTINES = ''; # get rid of -w warning
857 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
861 'URL_ENCODED'=> <<'END_OF_FUNC',
862 sub URL_ENCODED { 'application/x-www-form-urlencoded'; }
865 'MULTIPART' => <<'END_OF_FUNC',
866 sub MULTIPART { 'multipart/form-data'; }
869 'SERVER_PUSH' => <<'END_OF_FUNC',
870 sub SERVER_PUSH { 'multipart/x-mixed-replace;boundary="' . shift() . '"'; }
873 'new_MultipartBuffer' => <<'END_OF_FUNC',
874 # Create a new multipart buffer
875 sub new_MultipartBuffer {
876 my($self,$boundary,$length) = @_;
877 return MultipartBuffer->new($self,$boundary,$length);
881 'read_from_client' => <<'END_OF_FUNC',
882 # Read data from a file handle
883 sub read_from_client {
884 my($self, $buff, $len, $offset) = @_;
885 local $^W=0; # prevent a warning
887 ? $self->r->read($$buff, $len, $offset)
888 : read(\*STDIN, $$buff, $len, $offset);
892 'delete' => <<'END_OF_FUNC',
894 # Deletes the named parameter entirely.
897 my($self,@p) = self_or_default(@_);
898 my(@names) = rearrange([NAME],@p);
899 my @to_delete = ref($names[0]) eq 'ARRAY' ? @$names[0] : @names;
901 foreach my $name (@to_delete)
903 CORE::delete $self->{$name};
904 CORE::delete $self->{'.fieldnames'}->{$name};
907 @{$self->{'.parameters'}}=grep { !exists($to_delete{$_}) } $self->param();
908 return wantarray ? () : undef;
912 #### Method: import_names
913 # Import all parameters into the given namespace.
914 # Assumes namespace 'Q' if not specified
916 'import_names' => <<'END_OF_FUNC',
918 my($self,$namespace,$delete) = self_or_default(@_);
919 $namespace = 'Q' unless defined($namespace);
920 die "Can't import names into \"main\"\n" if \%{"${namespace}::"} == \%::;
921 if ($delete || $MOD_PERL || exists $ENV{'FCGI_ROLE'}) {
922 # can anyone find an easier way to do this?
923 foreach (keys %{"${namespace}::"}) {
924 local *symbol = "${namespace}::${_}";
930 my($param,@value,$var);
931 foreach $param ($self->param) {
932 # protect against silly names
933 ($var = $param)=~tr/a-zA-Z0-9_/_/c;
934 $var =~ s/^(?=\d)/_/;
935 local *symbol = "${namespace}::$var";
936 @value = $self->param($param);
943 #### Method: keywords
944 # Keywords acts a bit differently. Calling it in a list context
945 # returns the list of keywords.
946 # Calling it in a scalar context gives you the size of the list.
948 'keywords' => <<'END_OF_FUNC',
950 my($self,@values) = self_or_default(@_);
951 # If values is provided, then we set it.
952 $self->{'keywords'}=[@values] if @values;
953 my(@result) = defined($self->{'keywords'}) ? @{$self->{'keywords'}} : ();
958 # These are some tie() interfaces for compatibility
959 # with Steve Brenner's cgi-lib.pl routines
960 'Vars' => <<'END_OF_FUNC',
965 return %in if wantarray;
970 # These are some tie() interfaces for compatibility
971 # with Steve Brenner's cgi-lib.pl routines
972 'ReadParse' => <<'END_OF_FUNC',
982 return scalar(keys %in);
986 'PrintHeader' => <<'END_OF_FUNC',
988 my($self) = self_or_default(@_);
989 return $self->header();
993 'HtmlTop' => <<'END_OF_FUNC',
995 my($self,@p) = self_or_default(@_);
996 return $self->start_html(@p);
1000 'HtmlBot' => <<'END_OF_FUNC',
1002 my($self,@p) = self_or_default(@_);
1003 return $self->end_html(@p);
1007 'SplitParam' => <<'END_OF_FUNC',
1010 my (@params) = split ("\0", $param);
1011 return (wantarray ? @params : $params[0]);
1015 'MethGet' => <<'END_OF_FUNC',
1017 return request_method() eq 'GET';
1021 'MethPost' => <<'END_OF_FUNC',
1023 return request_method() eq 'POST';
1027 'TIEHASH' => <<'END_OF_FUNC',
1031 if (ref($arg) && UNIVERSAL::isa($arg,'CGI')) {
1034 return $Q ||= $class->new(@_);
1038 'STORE' => <<'END_OF_FUNC',
1043 my @vals = index($vals,"\0")!=-1 ? split("\0",$vals) : $vals;
1044 $self->param(-name=>$tag,-value=>\@vals);
1048 'FETCH' => <<'END_OF_FUNC',
1050 return $_[0] if $_[1] eq 'CGI';
1051 return undef unless defined $_[0]->param($_[1]);
1052 return join("\0",$_[0]->param($_[1]));
1056 'FIRSTKEY' => <<'END_OF_FUNC',
1058 $_[0]->{'.iterator'}=0;
1059 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1063 'NEXTKEY' => <<'END_OF_FUNC',
1065 $_[0]->{'.parameters'}->[$_[0]->{'.iterator'}++];
1069 'EXISTS' => <<'END_OF_FUNC',
1071 exists $_[0]->{$_[1]};
1075 'DELETE' => <<'END_OF_FUNC',
1077 $_[0]->delete($_[1]);
1081 'CLEAR' => <<'END_OF_FUNC',
1089 # Append a new value to an existing query
1091 'append' => <<'EOF',
1094 my($name,$value) = rearrange([NAME,[VALUE,VALUES]],@p);
1095 my(@values) = defined($value) ? (ref($value) ? @{$value} : $value) : ();
1097 $self->add_parameter($name);
1098 push(@{$self->{$name}},@values);
1100 return $self->param($name);
1104 #### Method: delete_all
1105 # Delete all parameters
1107 'delete_all' => <<'EOF',
1109 my($self) = self_or_default(@_);
1110 my @param = $self->param();
1111 $self->delete(@param);
1115 'Delete' => <<'EOF',
1117 my($self,@p) = self_or_default(@_);
1122 'Delete_all' => <<'EOF',
1124 my($self,@p) = self_or_default(@_);
1125 $self->delete_all(@p);
1129 #### Method: autoescape
1130 # If you want to turn off the autoescaping features,
1131 # call this method with undef as the argument
1132 'autoEscape' => <<'END_OF_FUNC',
1134 my($self,$escape) = self_or_default(@_);
1135 my $d = $self->{'escape'};
1136 $self->{'escape'} = $escape;
1142 #### Method: version
1143 # Return the current version
1145 'version' => <<'END_OF_FUNC',
1151 #### Method: url_param
1152 # Return a parameter in the QUERY_STRING, regardless of
1153 # whether this was a POST or a GET
1155 'url_param' => <<'END_OF_FUNC',
1157 my ($self,@p) = self_or_default(@_);
1158 my $name = shift(@p);
1159 return undef unless exists($ENV{QUERY_STRING});
1160 unless (exists($self->{'.url_param'})) {
1161 $self->{'.url_param'}={}; # empty hash
1162 if ($ENV{QUERY_STRING} =~ /=/) {
1163 my(@pairs) = split(/[&;]/,$ENV{QUERY_STRING});
1166 ($param,$value) = split('=',$_,2);
1167 $param = unescape($param);
1168 $value = unescape($value);
1169 push(@{$self->{'.url_param'}->{$param}},$value);
1172 $self->{'.url_param'}->{'keywords'} = [$self->parse_keywordlist($ENV{QUERY_STRING})];
1175 return keys %{$self->{'.url_param'}} unless defined($name);
1176 return () unless $self->{'.url_param'}->{$name};
1177 return wantarray ? @{$self->{'.url_param'}->{$name}}
1178 : $self->{'.url_param'}->{$name}->[0];
1183 # Returns a string in which all the known parameter/value
1184 # pairs are represented as nested lists, mainly for the purposes
1187 'Dump' => <<'END_OF_FUNC',
1189 my($self) = self_or_default(@_);
1190 my($param,$value,@result);
1191 return '<ul></ul>' unless $self->param;
1192 push(@result,"<ul>");
1193 foreach $param ($self->param) {
1194 my($name)=$self->escapeHTML($param);
1195 push(@result,"<li><strong>$param</strong></li>");
1196 push(@result,"<ul>");
1197 foreach $value ($self->param($param)) {
1198 $value = $self->escapeHTML($value);
1199 $value =~ s/\n/<br \/>\n/g;
1200 push(@result,"<li>$value</li>");
1202 push(@result,"</ul>");
1204 push(@result,"</ul>");
1205 return join("\n",@result);
1209 #### Method as_string
1211 # synonym for "dump"
1213 'as_string' => <<'END_OF_FUNC',
1220 # Write values out to a filehandle in such a way that they can
1221 # be reinitialized by the filehandle form of the new() method
1223 'save' => <<'END_OF_FUNC',
1225 my($self,$filehandle) = self_or_default(@_);
1226 $filehandle = to_filehandle($filehandle);
1228 local($,) = ''; # set print field separator back to a sane value
1229 local($\) = ''; # set output line separator to a sane value
1230 foreach $param ($self->param) {
1231 my($escaped_param) = escape($param);
1233 foreach $value ($self->param($param)) {
1234 print $filehandle "$escaped_param=",escape("$value"),"\n";
1237 foreach (keys %{$self->{'.fieldnames'}}) {
1238 print $filehandle ".cgifields=",escape("$_"),"\n";
1240 print $filehandle "=\n"; # end of record
1245 #### Method: save_parameters
1246 # An alias for save() that is a better name for exportation.
1247 # Only intended to be used with the function (non-OO) interface.
1249 'save_parameters' => <<'END_OF_FUNC',
1250 sub save_parameters {
1252 return save(to_filehandle($fh));
1256 #### Method: restore_parameters
1257 # A way to restore CGI parameters from an initializer.
1258 # Only intended to be used with the function (non-OO) interface.
1260 'restore_parameters' => <<'END_OF_FUNC',
1261 sub restore_parameters {
1262 $Q = $CGI::DefaultClass->new(@_);
1266 #### Method: multipart_init
1267 # Return a Content-Type: style header for server-push
1268 # This has to be NPH on most web servers, and it is advisable to set $| = 1
1270 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1271 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1273 'multipart_init' => <<'END_OF_FUNC',
1274 sub multipart_init {
1275 my($self,@p) = self_or_default(@_);
1276 my($boundary,@other) = rearrange([BOUNDARY],@p);
1277 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1278 $self->{'separator'} = "$CRLF--$boundary$CRLF";
1279 $self->{'final_separator'} = "$CRLF--$boundary--$CRLF";
1280 $type = SERVER_PUSH($boundary);
1281 return $self->header(
1284 (map { split "=", $_, 2 } @other),
1285 ) . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $self->multipart_end;
1290 #### Method: multipart_start
1291 # Return a Content-Type: style header for server-push, start of section
1293 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1294 # contribution, updated by Andrew Benham (adsb@bigfoot.com)
1296 'multipart_start' => <<'END_OF_FUNC',
1297 sub multipart_start {
1299 my($self,@p) = self_or_default(@_);
1300 my($type,@other) = rearrange([TYPE],@p);
1301 $type = $type || 'text/html';
1302 push(@header,"Content-Type: $type");
1304 # rearrange() was designed for the HTML portion, so we
1305 # need to fix it up a little.
1307 # Don't use \s because of perl bug 21951
1308 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1309 ($_ = $header) =~ s/^(\w)(.*)/$1 . lc ($2) . ': '.$self->unescapeHTML($value)/e;
1311 push(@header,@other);
1312 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1318 #### Method: multipart_end
1319 # Return a MIME boundary separator for server-push, end of section
1321 # Many thanks to Ed Jordan <ed@fidalgo.net> for this
1324 'multipart_end' => <<'END_OF_FUNC',
1326 my($self,@p) = self_or_default(@_);
1327 return $self->{'separator'};
1332 #### Method: multipart_final
1333 # Return a MIME boundary separator for server-push, end of all sections
1335 # Contributed by Andrew Benham (adsb@bigfoot.com)
1337 'multipart_final' => <<'END_OF_FUNC',
1338 sub multipart_final {
1339 my($self,@p) = self_or_default(@_);
1340 return $self->{'final_separator'} . "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY." . $CRLF;
1346 # Return a Content-Type: style header
1349 'header' => <<'END_OF_FUNC',
1351 my($self,@p) = self_or_default(@_);
1354 return "" if $self->{'.header_printed'}++ and $HEADERS_ONCE;
1356 my($type,$status,$cookie,$target,$expires,$nph,$charset,$attachment,$p3p,@other) =
1357 rearrange([['TYPE','CONTENT_TYPE','CONTENT-TYPE'],
1358 'STATUS',['COOKIE','COOKIES'],'TARGET',
1359 'EXPIRES','NPH','CHARSET',
1360 'ATTACHMENT','P3P'],@p);
1363 if (defined $charset) {
1364 $self->charset($charset);
1366 $charset = $self->charset;
1369 # rearrange() was designed for the HTML portion, so we
1370 # need to fix it up a little.
1372 # Don't use \s because of perl bug 21951
1373 next unless my($header,$value) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1374 ($_ = $header) =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e;
1377 $type ||= 'text/html' unless defined($type);
1378 $type .= "; charset=$charset" if $type ne '' and $type =~ m!^text/! and $type !~ /\bcharset\b/ and $charset ne '';
1380 # Maybe future compatibility. Maybe not.
1381 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1382 push(@header,$protocol . ' ' . ($status || '200 OK')) if $nph;
1383 push(@header,"Server: " . &server_software()) if $nph;
1385 push(@header,"Status: $status") if $status;
1386 push(@header,"Window-Target: $target") if $target;
1388 $p3p = join ' ',@$p3p if ref($p3p) eq 'ARRAY';
1389 push(@header,qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p"));
1391 # push all the cookies -- there may be several
1393 my(@cookie) = ref($cookie) && ref($cookie) eq 'ARRAY' ? @{$cookie} : $cookie;
1395 my $cs = UNIVERSAL::isa($_,'CGI::Cookie') ? $_->as_string : $_;
1396 push(@header,"Set-Cookie: $cs") if $cs ne '';
1399 # if the user indicates an expiration time, then we need
1400 # both an Expires and a Date header (so that the browser is
1402 push(@header,"Expires: " . expires($expires,'http'))
1404 push(@header,"Date: " . expires(0,'http')) if $expires || $cookie || $nph;
1405 push(@header,"Pragma: no-cache") if $self->cache();
1406 push(@header,"Content-Disposition: attachment; filename=\"$attachment\"") if $attachment;
1407 push(@header,map {ucfirst $_} @other);
1408 push(@header,"Content-Type: $type") if $type ne '';
1409 my $header = join($CRLF,@header)."${CRLF}${CRLF}";
1410 if ($MOD_PERL and not $nph) {
1411 $self->r->send_cgi_header($header);
1420 # Control whether header() will produce the no-cache
1423 'cache' => <<'END_OF_FUNC',
1425 my($self,$new_value) = self_or_default(@_);
1426 $new_value = '' unless $new_value;
1427 if ($new_value ne '') {
1428 $self->{'cache'} = $new_value;
1430 return $self->{'cache'};
1435 #### Method: redirect
1436 # Return a Location: style header
1439 'redirect' => <<'END_OF_FUNC',
1441 my($self,@p) = self_or_default(@_);
1442 my($url,$target,$cookie,$nph,@other) = rearrange([[LOCATION,URI,URL],TARGET,['COOKIE','COOKIES'],NPH],@p);
1443 $url ||= $self->self_url;
1445 foreach (@other) { tr/\"//d; push(@o,split("=",$_,2)); }
1447 '-Status' => '302 Moved',
1450 unshift(@o,'-Target'=>$target) if $target;
1451 unshift(@o,'-Type'=>'');
1453 unshift(@unescaped,'-Cookie'=>$cookie) if $cookie;
1454 return $self->header((map {$self->unescapeHTML($_)} @o),@unescaped);
1459 #### Method: start_html
1460 # Canned HTML header
1463 # $title -> (optional) The title for this HTML document (-title)
1464 # $author -> (optional) e-mail address of the author (-author)
1465 # $base -> (optional) if set to true, will enter the BASE address of this document
1466 # for resolving relative references (-base)
1467 # $xbase -> (optional) alternative base at some remote location (-xbase)
1468 # $target -> (optional) target window to load all links into (-target)
1469 # $script -> (option) Javascript code (-script)
1470 # $no_script -> (option) Javascript <noscript> tag (-noscript)
1471 # $meta -> (optional) Meta information tags
1472 # $head -> (optional) any other elements you'd like to incorporate into the <head> tag
1473 # (a scalar or array ref)
1474 # $style -> (optional) reference to an external style sheet
1475 # @other -> (optional) any other named parameters you'd like to incorporate into
1478 'start_html' => <<'END_OF_FUNC',
1480 my($self,@p) = &self_or_default(@_);
1481 my($title,$author,$base,$xbase,$script,$noscript,
1482 $target,$meta,$head,$style,$dtd,$lang,$encoding,@other) =
1483 rearrange([TITLE,AUTHOR,BASE,XBASE,SCRIPT,NOSCRIPT,TARGET,META,HEAD,STYLE,DTD,LANG,ENCODING],@p);
1485 $encoding = 'iso-8859-1' unless defined $encoding;
1487 # strangely enough, the title needs to be escaped as HTML
1488 # while the author needs to be escaped as a URL
1489 $title = $self->escapeHTML($title || 'Untitled Document');
1490 $author = $self->escape($author);
1491 $lang = 'en-US' unless defined $lang;
1492 my(@result,$xml_dtd);
1494 if (defined(ref($dtd)) and (ref($dtd) eq 'ARRAY')) {
1495 $dtd = $DEFAULT_DTD unless $dtd->[0] =~ m|^-//|;
1497 $dtd = $DEFAULT_DTD unless $dtd =~ m|^-//|;
1500 $dtd = $XHTML ? XHTML_DTD : $DEFAULT_DTD;
1503 $xml_dtd++ if ref($dtd) eq 'ARRAY' && $dtd->[0] =~ /\bXHTML\b/i;
1504 $xml_dtd++ if ref($dtd) eq '' && $dtd =~ /\bXHTML\b/i;
1505 push @result,qq(<?xml version="1.0" encoding="$encoding"?>) if $xml_dtd;
1507 if (ref($dtd) && ref($dtd) eq 'ARRAY') {
1508 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd->[0]"\n\t "$dtd->[1]">));
1510 push(@result,qq(<!DOCTYPE html\n\tPUBLIC "$dtd">));
1512 push(@result,$XHTML ? qq(<html xmlns="http://www.w3.org/1999/xhtml" lang="$lang" xml:lang="$lang"><head><title>$title</title>)
1513 : ($lang ? qq(<html lang="$lang">) : "<html>")
1514 . "<head><title>$title</title>");
1515 if (defined $author) {
1516 push(@result,$XHTML ? "<link rev=\"made\" href=\"mailto:$author\" />"
1517 : "<link rev=\"made\" href=\"mailto:$author\">");
1520 if ($base || $xbase || $target) {
1521 my $href = $xbase || $self->url('-path'=>1);
1522 my $t = $target ? qq/ target="$target"/ : '';
1523 push(@result,$XHTML ? qq(<base href="$href"$t />) : qq(<base href="$href"$t>));
1526 if ($meta && ref($meta) && (ref($meta) eq 'HASH')) {
1527 foreach (keys %$meta) { push(@result,$XHTML ? qq(<meta name="$_" content="$meta->{$_}" />)
1528 : qq(<meta name="$_" content="$meta->{$_}">)); }
1531 push(@result,ref($head) ? @$head : $head) if $head;
1533 # handle the infrequently-used -style and -script parameters
1534 push(@result,$self->_style($style)) if defined $style;
1535 push(@result,$self->_script($script)) if defined $script;
1537 # handle -noscript parameter
1538 push(@result,<<END) if $noscript;
1544 my($other) = @other ? " @other" : '';
1545 push(@result,"</head><body$other>");
1546 return join("\n",@result);
1551 # internal method for generating a CSS style section
1553 '_style' => <<'END_OF_FUNC',
1555 my ($self,$style) = @_;
1557 my $type = 'text/css';
1559 my $cdata_start = $XHTML ? "\n<!--/* <![CDATA[ */" : "\n<!-- ";
1560 my $cdata_end = $XHTML ? "\n/* ]]> */-->\n" : " -->\n";
1563 my($src,$code,$verbatim,$stype,$foo,@other) =
1564 rearrange([SRC,CODE,VERBATIM,TYPE],
1565 '-foo'=>'bar', # trick to allow dash to be omitted
1566 ref($style) eq 'ARRAY' ? @$style : %$style);
1567 $type = $stype if $stype;
1568 my $other = @other ? join ' ',@other : '';
1570 if (ref($src) eq "ARRAY") # Check to see if the $src variable is an array reference
1571 { # If it is, push a LINK tag for each one
1572 foreach $src (@$src)
1574 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1575 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)) if $src;
1579 { # Otherwise, push the single -src, if it exists.
1580 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1581 : qq(<link rel="stylesheet" type="$type" href="$src"$other>)
1585 push(@result, "<style type=\"text/css\">\n$verbatim\n</style>");
1587 push(@result,style({'type'=>$type},"$cdata_start\n$code\n$cdata_end")) if $code;
1590 push(@result,$XHTML ? qq(<link rel="stylesheet" type="$type" href="$src" $other/>)
1591 : qq(<link rel="stylesheet" type="$type" href="$src"$other>));
1597 '_script' => <<'END_OF_FUNC',
1599 my ($self,$script) = @_;
1602 my (@scripts) = ref($script) eq 'ARRAY' ? @$script : ($script);
1603 foreach $script (@scripts) {
1604 my($src,$code,$language);
1605 if (ref($script)) { # script is a hash
1606 ($src,$code,$language, $type) =
1607 rearrange([SRC,CODE,LANGUAGE,TYPE],
1608 '-foo'=>'bar', # a trick to allow the '-' to be omitted
1609 ref($script) eq 'ARRAY' ? @$script : %$script);
1610 # User may not have specified language
1611 $language ||= 'JavaScript';
1612 unless (defined $type) {
1613 $type = lc $language;
1614 # strip '1.2' from 'javascript1.2'
1615 $type =~ s/^(\D+).*$/text\/$1/;
1618 ($src,$code,$language, $type) = ('',$script,'JavaScript', 'text/javascript');
1621 my $comment = '//'; # javascript by default
1622 $comment = '#' if $type=~/perl|tcl/i;
1623 $comment = "'" if $type=~/vbscript/i;
1625 my ($cdata_start,$cdata_end);
1627 $cdata_start = "$comment<![CDATA[\n";
1628 $cdata_end .= "\n$comment]]>";
1630 $cdata_start = "\n<!-- Hide script\n";
1631 $cdata_end = $comment;
1632 $cdata_end .= " End script hiding -->\n";
1635 push(@satts,'src'=>$src) if $src;
1636 push(@satts,'language'=>$language) unless defined $type;
1637 push(@satts,'type'=>$type);
1638 $code = "$cdata_start$code$cdata_end" if defined $code;
1639 push(@result,script({@satts},$code || ''));
1645 #### Method: end_html
1646 # End an HTML document.
1647 # Trivial method for completeness. Just returns "</body>"
1649 'end_html' => <<'END_OF_FUNC',
1651 return "</body></html>";
1656 ################################
1657 # METHODS USED IN BUILDING FORMS
1658 ################################
1660 #### Method: isindex
1661 # Just prints out the isindex tag.
1663 # $action -> optional URL of script to run
1665 # A string containing a <isindex> tag
1666 'isindex' => <<'END_OF_FUNC',
1668 my($self,@p) = self_or_default(@_);
1669 my($action,@other) = rearrange([ACTION],@p);
1670 $action = qq/ action="$action"/ if $action;
1671 my($other) = @other ? " @other" : '';
1672 return $XHTML ? "<isindex$action$other />" : "<isindex$action$other>";
1677 #### Method: startform
1680 # $method -> optional submission method to use (GET or POST)
1681 # $action -> optional URL of script to run
1682 # $enctype ->encoding to use (URL_ENCODED or MULTIPART)
1683 'startform' => <<'END_OF_FUNC',
1685 my($self,@p) = self_or_default(@_);
1687 my($method,$action,$enctype,@other) =
1688 rearrange([METHOD,ACTION,ENCTYPE],@p);
1690 $method = lc($method) || 'post';
1691 $enctype = $enctype || &URL_ENCODED;
1692 unless (defined $action) {
1694 $action = $self->escapeHTML($self->url(-absolute=>1,-path=>1));
1695 if (length($ENV{QUERY_STRING})>0) {
1696 $action .= "?".$self->escapeHTML($ENV{QUERY_STRING},1);
1699 $action = qq(action="$action");
1700 my($other) = @other ? " @other" : '';
1701 $self->{'.parametersToAdd'}={};
1702 return qq/<form method="$method" $action enctype="$enctype"$other>\n/;
1707 #### Method: start_form
1708 # synonym for startform
1709 'start_form' => <<'END_OF_FUNC',
1715 'end_multipart_form' => <<'END_OF_FUNC',
1716 sub end_multipart_form {
1721 #### Method: start_multipart_form
1722 # synonym for startform
1723 'start_multipart_form' => <<'END_OF_FUNC',
1724 sub start_multipart_form {
1725 my($self,@p) = self_or_default(@_);
1726 if (defined($param[0]) && substr($param[0],0,1) eq '-') {
1728 $p{'-enctype'}=&MULTIPART;
1729 return $self->startform(%p);
1731 my($method,$action,@other) =
1732 rearrange([METHOD,ACTION],@p);
1733 return $self->startform($method,$action,&MULTIPART,@other);
1739 #### Method: endform
1741 'endform' => <<'END_OF_FUNC',
1743 my($self,@p) = self_or_default(@_);
1745 return wantarray ? ("</form>") : "\n</form>";
1747 return wantarray ? ("<div>",$self->get_fields,"</div>","</form>") :
1748 "<div>".$self->get_fields ."</div>\n</form>";
1754 #### Method: end_form
1755 # synonym for endform
1756 'end_form' => <<'END_OF_FUNC',
1763 '_textfield' => <<'END_OF_FUNC',
1765 my($self,$tag,@p) = self_or_default(@_);
1766 my($name,$default,$size,$maxlength,$override,@other) =
1767 rearrange([NAME,[DEFAULT,VALUE,VALUES],SIZE,MAXLENGTH,[OVERRIDE,FORCE]],@p);
1769 my $current = $override ? $default :
1770 (defined($self->param($name)) ? $self->param($name) : $default);
1772 $current = defined($current) ? $self->escapeHTML($current,1) : '';
1773 $name = defined($name) ? $self->escapeHTML($name) : '';
1774 my($s) = defined($size) ? qq/ size="$size"/ : '';
1775 my($m) = defined($maxlength) ? qq/ maxlength="$maxlength"/ : '';
1776 my($other) = @other ? " @other" : '';
1777 # this entered at cristy's request to fix problems with file upload fields
1778 # and WebTV -- not sure it won't break stuff
1779 my($value) = $current ne '' ? qq(value="$current") : '';
1780 return $XHTML ? qq(<input type="$tag" name="$name" $value$s$m$other />)
1781 : qq(<input type="$tag" name="$name" $value$s$m$other>);
1785 #### Method: textfield
1787 # $name -> Name of the text field
1788 # $default -> Optional default value of the field if not
1790 # $size -> Optional width of field in characaters.
1791 # $maxlength -> Optional maximum number of characters.
1793 # A string containing a <input type="text"> field
1795 'textfield' => <<'END_OF_FUNC',
1797 my($self,@p) = self_or_default(@_);
1798 $self->_textfield('text',@p);
1803 #### Method: filefield
1805 # $name -> Name of the file upload field
1806 # $size -> Optional width of field in characaters.
1807 # $maxlength -> Optional maximum number of characters.
1809 # A string containing a <input type="file"> field
1811 'filefield' => <<'END_OF_FUNC',
1813 my($self,@p) = self_or_default(@_);
1814 $self->_textfield('file',@p);
1819 #### Method: password
1820 # Create a "secret password" entry field
1822 # $name -> Name of the field
1823 # $default -> Optional default value of the field if not
1825 # $size -> Optional width of field in characters.
1826 # $maxlength -> Optional maximum characters that can be entered.
1828 # A string containing a <input type="password"> field
1830 'password_field' => <<'END_OF_FUNC',
1831 sub password_field {
1832 my ($self,@p) = self_or_default(@_);
1833 $self->_textfield('password',@p);
1837 #### Method: textarea
1839 # $name -> Name of the text field
1840 # $default -> Optional default value of the field if not
1842 # $rows -> Optional number of rows in text area
1843 # $columns -> Optional number of columns in text area
1845 # A string containing a <textarea></textarea> tag
1847 'textarea' => <<'END_OF_FUNC',
1849 my($self,@p) = self_or_default(@_);
1851 my($name,$default,$rows,$cols,$override,@other) =
1852 rearrange([NAME,[DEFAULT,VALUE],ROWS,[COLS,COLUMNS],[OVERRIDE,FORCE]],@p);
1854 my($current)= $override ? $default :
1855 (defined($self->param($name)) ? $self->param($name) : $default);
1857 $name = defined($name) ? $self->escapeHTML($name) : '';
1858 $current = defined($current) ? $self->escapeHTML($current) : '';
1859 my($r) = $rows ? qq/ rows="$rows"/ : '';
1860 my($c) = $cols ? qq/ cols="$cols"/ : '';
1861 my($other) = @other ? " @other" : '';
1862 return qq{<textarea name="$name"$r$c$other>$current</textarea>};
1868 # Create a javascript button.
1870 # $name -> (optional) Name for the button. (-name)
1871 # $value -> (optional) Value of the button when selected (and visible name) (-value)
1872 # $onclick -> (optional) Text of the JavaScript to run when the button is
1875 # A string containing a <input type="button"> tag
1877 'button' => <<'END_OF_FUNC',
1879 my($self,@p) = self_or_default(@_);
1881 my($label,$value,$script,@other) = rearrange([NAME,[VALUE,LABEL],
1882 [ONCLICK,SCRIPT]],@p);
1884 $label=$self->escapeHTML($label);
1885 $value=$self->escapeHTML($value,1);
1886 $script=$self->escapeHTML($script);
1889 $name = qq/ name="$label"/ if $label;
1890 $value = $value || $label;
1892 $val = qq/ value="$value"/ if $value;
1893 $script = qq/ onclick="$script"/ if $script;
1894 my($other) = @other ? " @other" : '';
1895 return $XHTML ? qq(<input type="button"$name$val$script$other />)
1896 : qq(<input type="button"$name$val$script$other>);
1902 # Create a "submit query" button.
1904 # $name -> (optional) Name for the button.
1905 # $value -> (optional) Value of the button when selected (also doubles as label).
1906 # $label -> (optional) Label printed on the button(also doubles as the value).
1908 # A string containing a <input type="submit"> tag
1910 'submit' => <<'END_OF_FUNC',
1912 my($self,@p) = self_or_default(@_);
1914 my($label,$value,@other) = rearrange([NAME,[VALUE,LABEL]],@p);
1916 $label=$self->escapeHTML($label);
1917 $value=$self->escapeHTML($value,1);
1919 my $name = $NOSTICKY ? '' : ' name=".submit"';
1920 $name = qq/ name="$label"/ if defined($label);
1921 $value = defined($value) ? $value : $label;
1923 $val = qq/ value="$value"/ if defined($value);
1924 my($other) = @other ? " @other" : '';
1925 return $XHTML ? qq(<input type="submit"$name$val$other />)
1926 : qq(<input type="submit"$name$val$other>);
1932 # Create a "reset" button.
1934 # $name -> (optional) Name for the button.
1936 # A string containing a <input type="reset"> tag
1938 'reset' => <<'END_OF_FUNC',
1940 my($self,@p) = self_or_default(@_);
1941 my($label,$value,@other) = rearrange(['NAME',['VALUE','LABEL']],@p);
1942 $label=$self->escapeHTML($label);
1943 $value=$self->escapeHTML($value,1);
1944 my ($name) = ' name=".reset"';
1945 $name = qq/ name="$label"/ if defined($label);
1946 $value = defined($value) ? $value : $label;
1948 $val = qq/ value="$value"/ if defined($value);
1949 my($other) = @other ? " @other" : '';
1950 return $XHTML ? qq(<input type="reset"$name$val$other />)
1951 : qq(<input type="reset"$name$val$other>);
1956 #### Method: defaults
1957 # Create a "defaults" button.
1959 # $name -> (optional) Name for the button.
1961 # A string containing a <input type="submit" name=".defaults"> tag
1963 # Note: this button has a special meaning to the initialization script,
1964 # and tells it to ERASE the current query string so that your defaults
1967 'defaults' => <<'END_OF_FUNC',
1969 my($self,@p) = self_or_default(@_);
1971 my($label,@other) = rearrange([[NAME,VALUE]],@p);
1973 $label=$self->escapeHTML($label,1);
1974 $label = $label || "Defaults";
1975 my($value) = qq/ value="$label"/;
1976 my($other) = @other ? " @other" : '';
1977 return $XHTML ? qq(<input type="submit" name=".defaults"$value$other />)
1978 : qq/<input type="submit" NAME=".defaults"$value$other>/;
1983 #### Method: comment
1984 # Create an HTML <!-- comment -->
1985 # Parameters: a string
1986 'comment' => <<'END_OF_FUNC',
1988 my($self,@p) = self_or_CGI(@_);
1989 return "<!-- @p -->";
1993 #### Method: checkbox
1994 # Create a checkbox that is not logically linked to any others.
1995 # The field value is "on" when the button is checked.
1997 # $name -> Name of the checkbox
1998 # $checked -> (optional) turned on by default if true
1999 # $value -> (optional) value of the checkbox, 'on' by default
2000 # $label -> (optional) a user-readable label printed next to the box.
2001 # Otherwise the checkbox name is used.
2003 # A string containing a <input type="checkbox"> field
2005 'checkbox' => <<'END_OF_FUNC',
2007 my($self,@p) = self_or_default(@_);
2009 my($name,$checked,$value,$label,$override,@other) =
2010 rearrange([NAME,[CHECKED,SELECTED,ON],VALUE,LABEL,[OVERRIDE,FORCE]],@p);
2012 $value = defined $value ? $value : 'on';
2014 if (!$override && ($self->{'.fieldnames'}->{$name} ||
2015 defined $self->param($name))) {
2016 $checked = grep($_ eq $value,$self->param($name)) ? $self->_checked(1) : '';
2018 $checked = $self->_checked($checked);
2020 my($the_label) = defined $label ? $label : $name;
2021 $name = $self->escapeHTML($name);
2022 $value = $self->escapeHTML($value,1);
2023 $the_label = $self->escapeHTML($the_label);
2024 my($other) = @other ? " @other" : '';
2025 $self->register_parameter($name);
2026 return $XHTML ? qq{<input type="checkbox" name="$name" value="$value"$checked$other />$the_label}
2027 : qq{<input type="checkbox" name="$name" value="$value"$checked$other>$the_label};
2032 #### Method: checkbox_group
2033 # Create a list of logically-linked checkboxes.
2035 # $name -> Common name for all the check boxes
2036 # $values -> A pointer to a regular array containing the
2037 # values for each checkbox in the group.
2038 # $defaults -> (optional)
2039 # 1. If a pointer to a regular array of checkbox values,
2040 # then this will be used to decide which
2041 # checkboxes to turn on by default.
2042 # 2. If a scalar, will be assumed to hold the
2043 # value of a single checkbox in the group to turn on.
2044 # $linebreak -> (optional) Set to true to place linebreaks
2045 # between the buttons.
2046 # $labels -> (optional)
2047 # A pointer to an associative array of labels to print next to each checkbox
2048 # in the form $label{'value'}="Long explanatory label".
2049 # Otherwise the provided values are used as the labels.
2051 # An ARRAY containing a series of <input type="checkbox"> fields
2053 'checkbox_group' => <<'END_OF_FUNC',
2054 sub checkbox_group {
2055 my($self,@p) = self_or_default(@_);
2057 my($name,$values,$defaults,$linebreak,$labels,$attributes,$rows,$columns,
2058 $rowheaders,$colheaders,$override,$nolabels,@other) =
2059 rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2060 LINEBREAK,LABELS,ATTRIBUTES,ROWS,[COLUMNS,COLS],
2061 ROWHEADERS,COLHEADERS,
2062 [OVERRIDE,FORCE],NOLABELS],@p);
2064 my($checked,$break,$result,$label);
2066 my(%checked) = $self->previous_or_default($name,$defaults,$override);
2069 $break = $XHTML ? "<br />" : "<br>";
2074 $name=$self->escapeHTML($name);
2076 # Create the elements
2077 my(@elements,@values);
2079 @values = $self->_set_values_and_labels($values,\$labels,$name);
2081 my($other) = @other ? " @other" : '';
2083 $checked = $self->_checked($checked{$_});
2085 unless (defined($nolabels) && $nolabels) {
2087 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2088 $label = $self->escapeHTML($label);
2090 my $attribs = $self->_set_attributes($_, $attributes);
2091 $_ = $self->escapeHTML($_,1);
2092 push(@elements,$XHTML ? qq(<input type="checkbox" name="$name" value="$_"$checked$other$attribs />${label}${break})
2093 : qq/<input type="checkbox" name="$name" value="$_"$checked$other$attribs>${label}${break}/);
2095 $self->register_parameter($name);
2096 return wantarray ? @elements : join(' ',@elements)
2097 unless defined($columns) || defined($rows);
2098 $rows = 1 if $rows && $rows < 1;
2099 $cols = 1 if $cols && $cols < 1;
2100 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2104 # Escape HTML -- used internally
2105 'escapeHTML' => <<'END_OF_FUNC',
2107 # hack to work around earlier hacks
2108 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
2109 my ($self,$toencode,$newlinestoo) = CGI::self_or_default(@_);
2110 return undef unless defined($toencode);
2111 return $toencode if ref($self) && !$self->{'escape'};
2112 $toencode =~ s{&}{&}gso;
2113 $toencode =~ s{<}{<}gso;
2114 $toencode =~ s{>}{>}gso;
2115 $toencode =~ s{"}{"}gso;
2116 my $latin = uc $self->{'.charset'} eq 'ISO-8859-1' ||
2117 uc $self->{'.charset'} eq 'WINDOWS-1252';
2118 if ($latin) { # bug in some browsers
2119 $toencode =~ s{'}{'}gso;
2120 $toencode =~ s{\x8b}{‹}gso;
2121 $toencode =~ s{\x9b}{›}gso;
2122 if (defined $newlinestoo && $newlinestoo) {
2123 $toencode =~ s{\012}{ }gso;
2124 $toencode =~ s{\015}{ }gso;
2131 # unescape HTML -- used internally
2132 'unescapeHTML' => <<'END_OF_FUNC',
2134 # hack to work around earlier hacks
2135 push @_,$_[0] if @_==1 && $_[0] eq 'CGI';
2136 my ($self,$string) = CGI::self_or_default(@_);
2137 return undef unless defined($string);
2138 my $latin = defined $self->{'.charset'} ? $self->{'.charset'} =~ /^(ISO-8859-1|WINDOWS-1252)$/i
2140 # thanks to Randal Schwartz for the correct solution to this one
2141 $string=~ s[&(.*?);]{
2147 /^#(\d+)$/ && $latin ? chr($1) :
2148 /^#x([0-9a-f]+)$/i && $latin ? chr(hex($1)) :
2155 # Internal procedure - don't use
2156 '_tableize' => <<'END_OF_FUNC',
2158 my($rows,$columns,$rowheaders,$colheaders,@elements) = @_;
2159 $rowheaders = [] unless defined $rowheaders;
2160 $colheaders = [] unless defined $colheaders;
2163 if (defined($columns)) {
2164 $rows = int(0.99 + @elements/$columns) unless defined($rows);
2166 if (defined($rows)) {
2167 $columns = int(0.99 + @elements/$rows) unless defined($columns);
2170 # rearrange into a pretty table
2171 $result = "<table>";
2173 unshift(@$colheaders,'') if @$colheaders && @$rowheaders;
2174 $result .= "<tr>" if @{$colheaders};
2175 foreach (@{$colheaders}) {
2176 $result .= "<th>$_</th>";
2178 for ($row=0;$row<$rows;$row++) {
2180 $result .= "<th>$rowheaders->[$row]</th>" if @$rowheaders;
2181 for ($column=0;$column<$columns;$column++) {
2182 $result .= "<td>" . $elements[$column*$rows + $row] . "</td>"
2183 if defined($elements[$column*$rows + $row]);
2187 $result .= "</table>";
2193 #### Method: radio_group
2194 # Create a list of logically-linked radio buttons.
2196 # $name -> Common name for all the buttons.
2197 # $values -> A pointer to a regular array containing the
2198 # values for each button in the group.
2199 # $default -> (optional) Value of the button to turn on by default. Pass '-'
2200 # to turn _nothing_ on.
2201 # $linebreak -> (optional) Set to true to place linebreaks
2202 # between the buttons.
2203 # $labels -> (optional)
2204 # A pointer to an associative array of labels to print next to each checkbox
2205 # in the form $label{'value'}="Long explanatory label".
2206 # Otherwise the provided values are used as the labels.
2208 # An ARRAY containing a series of <input type="radio"> fields
2210 'radio_group' => <<'END_OF_FUNC',
2212 my($self,@p) = self_or_default(@_);
2214 my($name,$values,$default,$linebreak,$labels,$attributes,
2215 $rows,$columns,$rowheaders,$colheaders,$override,$nolabels,@other) =
2216 rearrange([NAME,[VALUES,VALUE],DEFAULT,LINEBREAK,LABELS,ATTRIBUTES,
2217 ROWS,[COLUMNS,COLS],
2218 ROWHEADERS,COLHEADERS,
2219 [OVERRIDE,FORCE],NOLABELS],@p);
2220 my($result,$checked);
2222 if (!$override && defined($self->param($name))) {
2223 $checked = $self->param($name);
2225 $checked = $default;
2227 my(@elements,@values);
2228 @values = $self->_set_values_and_labels($values,\$labels,$name);
2230 # If no check array is specified, check the first by default
2231 $checked = $values[0] unless defined($checked) && $checked ne '';
2232 $name=$self->escapeHTML($name);
2234 my($other) = @other ? " @other" : '';
2236 my($checkit) = $checked eq $_ ? qq/ checked="checked"/ : '';
2239 $break = $XHTML ? "<br />" : "<br>";
2245 unless (defined($nolabels) && $nolabels) {
2247 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2248 $label = $self->escapeHTML($label,1);
2250 my $attribs = $self->_set_attributes($_, $attributes);
2251 $_=$self->escapeHTML($_);
2252 push(@elements,$XHTML ? qq(<input type="radio" name="$name" value="$_"$checkit$other$attribs />${label}${break})
2253 : qq/<input type="radio" name="$name" value="$_"$checkit$other$attribs>${label}${break}/);
2255 $self->register_parameter($name);
2256 return wantarray ? @elements : join(' ',@elements)
2257 unless defined($columns) || defined($rows);
2258 return _tableize($rows,$columns,$rowheaders,$colheaders,@elements);
2263 #### Method: popup_menu
2264 # Create a popup menu.
2266 # $name -> Name for all the menu
2267 # $values -> A pointer to a regular array containing the
2268 # text of each menu item.
2269 # $default -> (optional) Default item to display
2270 # $labels -> (optional)
2271 # A pointer to an associative array of labels to print next to each checkbox
2272 # in the form $label{'value'}="Long explanatory label".
2273 # Otherwise the provided values are used as the labels.
2275 # A string containing the definition of a popup menu.
2277 'popup_menu' => <<'END_OF_FUNC',
2279 my($self,@p) = self_or_default(@_);
2281 my($name,$values,$default,$labels,$attributes,$override,@other) =
2282 rearrange([NAME,[VALUES,VALUE],[DEFAULT,DEFAULTS],LABELS,
2283 ATTRIBUTES,[OVERRIDE,FORCE]],@p);
2284 my($result,$selected);
2286 if (!$override && defined($self->param($name))) {
2287 $selected = $self->param($name);
2289 $selected = $default;
2291 $name=$self->escapeHTML($name);
2292 my($other) = @other ? " @other" : '';
2295 @values = $self->_set_values_and_labels($values,\$labels,$name);
2297 $result = qq/<select name="$name"$other>\n/;
2300 foreach (split(/\n/)) {
2301 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2302 s/(value="$selected")/$selectit $1/ if defined $selected;
2307 my $attribs = $self->_set_attributes($_, $attributes);
2308 my($selectit) = defined($selected) ? $self->_selected($selected eq $_) : '';
2310 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2311 my($value) = $self->escapeHTML($_);
2312 $label=$self->escapeHTML($label,1);
2313 $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
2317 $result .= "</select>";
2323 #### Method: optgroup
2324 # Create a optgroup.
2326 # $name -> Label for the group
2327 # $values -> A pointer to a regular array containing the
2328 # values for each option line in the group.
2329 # $labels -> (optional)
2330 # A pointer to an associative array of labels to print next to each item
2331 # in the form $label{'value'}="Long explanatory label".
2332 # Otherwise the provided values are used as the labels.
2333 # $labeled -> (optional)
2334 # A true value indicates the value should be used as the label attribute
2335 # in the option elements.
2336 # The label attribute specifies the option label presented to the user.
2337 # This defaults to the content of the <option> element, but the label
2338 # attribute allows authors to more easily use optgroup without sacrificing
2339 # compatibility with browsers that do not support option groups.
2340 # $novals -> (optional)
2341 # A true value indicates to suppress the val attribute in the option elements
2343 # A string containing the definition of an option group.
2345 'optgroup' => <<'END_OF_FUNC',
2347 my($self,@p) = self_or_default(@_);
2348 my($name,$values,$attributes,$labeled,$noval,$labels,@other)
2349 = rearrange([NAME,[VALUES,VALUE],ATTRIBUTES,LABELED,NOVALS,LABELS],@p);
2351 my($result,@values);
2352 @values = $self->_set_values_and_labels($values,\$labels,$name,$labeled,$novals);
2353 my($other) = @other ? " @other" : '';
2355 $name=$self->escapeHTML($name);
2356 $result = qq/<optgroup label="$name"$other>\n/;
2359 foreach (split(/\n/)) {
2360 my $selectit = $XHTML ? 'selected="selected"' : 'selected';
2361 s/(value="$selected")/$selectit $1/ if defined $selected;
2366 my $attribs = $self->_set_attributes($_, $attributes);
2368 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2369 $label=$self->escapeHTML($label);
2370 my($value)=$self->escapeHTML($_,1);
2371 $result .= $labeled ? $novals ? "<option$attribs label=\"$value\">$label</option>\n"
2372 : "<option$attribs label=\"$value\" value=\"$value\">$label</option>\n"
2373 : $novals ? "<option$attribs>$label</option>\n"
2374 : "<option$attribs value=\"$value\">$label</option>\n";
2377 $result .= "</optgroup>";
2383 #### Method: scrolling_list
2384 # Create a scrolling list.
2386 # $name -> name for the list
2387 # $values -> A pointer to a regular array containing the
2388 # values for each option line in the list.
2389 # $defaults -> (optional)
2390 # 1. If a pointer to a regular array of options,
2391 # then this will be used to decide which
2392 # lines to turn on by default.
2393 # 2. Otherwise holds the value of the single line to turn on.
2394 # $size -> (optional) Size of the list.
2395 # $multiple -> (optional) If set, allow multiple selections.
2396 # $labels -> (optional)
2397 # A pointer to an associative array of labels to print next to each checkbox
2398 # in the form $label{'value'}="Long explanatory label".
2399 # Otherwise the provided values are used as the labels.
2401 # A string containing the definition of a scrolling list.
2403 'scrolling_list' => <<'END_OF_FUNC',
2404 sub scrolling_list {
2405 my($self,@p) = self_or_default(@_);
2406 my($name,$values,$defaults,$size,$multiple,$labels,$attributes,$override,@other)
2407 = rearrange([NAME,[VALUES,VALUE],[DEFAULTS,DEFAULT],
2408 SIZE,MULTIPLE,LABELS,ATTRIBUTES,[OVERRIDE,FORCE]],@p);
2410 my($result,@values);
2411 @values = $self->_set_values_and_labels($values,\$labels,$name);
2413 $size = $size || scalar(@values);
2415 my(%selected) = $self->previous_or_default($name,$defaults,$override);
2416 my($is_multiple) = $multiple ? qq/ multiple="multiple"/ : '';
2417 my($has_size) = $size ? qq/ size="$size"/: '';
2418 my($other) = @other ? " @other" : '';
2420 $name=$self->escapeHTML($name);
2421 $result = qq/<select name="$name"$has_size$is_multiple$other>\n/;
2423 my($selectit) = $self->_selected($selected{$_});
2425 $label = $labels->{$_} if defined($labels) && defined($labels->{$_});
2426 $label=$self->escapeHTML($label);
2427 my($value)=$self->escapeHTML($_,1);
2428 my $attribs = $self->_set_attributes($_, $attributes);
2429 $result .= "<option$selectit$attribs value=\"$value\">$label</option>\n";
2431 $result .= "</select>";
2432 $self->register_parameter($name);
2440 # $name -> Name of the hidden field
2441 # @default -> (optional) Initial values of field (may be an array)
2443 # $default->[initial values of field]
2445 # A string containing a <input type="hidden" name="name" value="value">
2447 'hidden' => <<'END_OF_FUNC',
2449 my($self,@p) = self_or_default(@_);
2451 # this is the one place where we departed from our standard
2452 # calling scheme, so we have to special-case (darn)
2454 my($name,$default,$override,@other) =
2455 rearrange([NAME,[DEFAULT,VALUE,VALUES],[OVERRIDE,FORCE]],@p);
2457 my $do_override = 0;
2458 if ( ref($p[0]) || substr($p[0],0,1) eq '-') {
2459 @value = ref($default) ? @{$default} : $default;
2460 $do_override = $override;
2462 foreach ($default,$override,@other) {
2463 push(@value,$_) if defined($_);
2467 # use previous values if override is not set
2468 my @prev = $self->param($name);
2469 @value = @prev if !$do_override && @prev;
2471 $name=$self->escapeHTML($name);
2473 $_ = defined($_) ? $self->escapeHTML($_,1) : '';
2474 push @result,$XHTML ? qq(<input type="hidden" name="$name" value="$_" />)
2475 : qq(<input type="hidden" name="$name" value="$_">);
2477 return wantarray ? @result : join('',@result);
2482 #### Method: image_button
2484 # $name -> Name of the button
2485 # $src -> URL of the image source
2486 # $align -> Alignment style (TOP, BOTTOM or MIDDLE)
2488 # A string containing a <input type="image" name="name" src="url" align="alignment">
2490 'image_button' => <<'END_OF_FUNC',
2492 my($self,@p) = self_or_default(@_);
2494 my($name,$src,$alignment,@other) =
2495 rearrange([NAME,SRC,ALIGN],@p);
2497 my($align) = $alignment ? " align=\U\"$alignment\"" : '';
2498 my($other) = @other ? " @other" : '';
2499 $name=$self->escapeHTML($name);
2500 return $XHTML ? qq(<input type="image" name="$name" src="$src"$align$other />)
2501 : qq/<input type="image" name="$name" src="$src"$align$other>/;
2506 #### Method: self_url
2507 # Returns a URL containing the current script and all its
2508 # param/value pairs arranged as a query. You can use this
2509 # to create a link that, when selected, will reinvoke the
2510 # script with all its state information preserved.
2512 'self_url' => <<'END_OF_FUNC',
2514 my($self,@p) = self_or_default(@_);
2515 return $self->url('-path_info'=>1,'-query'=>1,'-full'=>1,@p);
2520 # This is provided as a synonym to self_url() for people unfortunate
2521 # enough to have incorporated it into their programs already!
2522 'state' => <<'END_OF_FUNC',
2530 # Like self_url, but doesn't return the query string part of
2533 'url' => <<'END_OF_FUNC',
2535 my($self,@p) = self_or_default(@_);
2536 my ($relative,$absolute,$full,$path_info,$query,$base) =
2537 rearrange(['RELATIVE','ABSOLUTE','FULL',['PATH','PATH_INFO'],['QUERY','QUERY_STRING'],'BASE'],@p);
2539 $full++ if $base || !($relative || $absolute);
2541 my $path = $self->path_info;
2542 my $script_name = $self->script_name;
2544 # for compatibility with Apache's MultiViews
2545 if (exists($ENV{REQUEST_URI})) {
2547 $script_name = unescape($ENV{REQUEST_URI});
2548 $script_name =~ s/\?.+$//; # strip query string
2550 if (exists($ENV{PATH_INFO})) {
2551 my $encoded_path = unescape($ENV{PATH_INFO});
2552 $script_name =~ s/\Q$encoded_path\E$//i;
2557 my $protocol = $self->protocol();
2558 $url = "$protocol://";
2559 my $vh = http('host');
2563 $url .= server_name();
2564 my $port = $self->server_port;
2566 unless (lc($protocol) eq 'http' && $port == 80)
2567 || (lc($protocol) eq 'https' && $port == 443);
2569 return $url if $base;
2570 $url .= $script_name;
2571 } elsif ($relative) {
2572 ($url) = $script_name =~ m!([^/]+)$!;
2573 } elsif ($absolute) {
2574 $url = $script_name;
2577 $url .= $path if $path_info and defined $path;
2578 $url .= "?" . $self->query_string if $query and $self->query_string;
2579 $url = '' unless defined $url;
2580 $url =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/sprintf("%%%02X",ord($1))/eg;
2587 # Set or read a cookie from the specified name.
2588 # Cookie can then be passed to header().
2589 # Usual rules apply to the stickiness of -value.
2591 # -name -> name for this cookie (optional)
2592 # -value -> value of this cookie (scalar, array or hash)
2593 # -path -> paths for which this cookie is valid (optional)
2594 # -domain -> internet domain in which this cookie is valid (optional)
2595 # -secure -> if true, cookie only passed through secure channel (optional)
2596 # -expires -> expiry date in format Wdy, DD-Mon-YYYY HH:MM:SS GMT (optional)
2598 'cookie' => <<'END_OF_FUNC',
2600 my($self,@p) = self_or_default(@_);
2601 my($name,$value,$path,$domain,$secure,$expires) =
2602 rearrange([NAME,[VALUE,VALUES],PATH,DOMAIN,SECURE,EXPIRES],@p);
2604 require CGI::Cookie;
2606 # if no value is supplied, then we retrieve the
2607 # value of the cookie, if any. For efficiency, we cache the parsed
2608 # cookies in our state variables.
2609 unless ( defined($value) ) {
2610 $self->{'.cookies'} = CGI::Cookie->fetch
2611 unless $self->{'.cookies'};
2613 # If no name is supplied, then retrieve the names of all our cookies.
2614 return () unless $self->{'.cookies'};
2615 return keys %{$self->{'.cookies'}} unless $name;
2616 return () unless $self->{'.cookies'}->{$name};
2617 return $self->{'.cookies'}->{$name}->value if defined($name) && $name ne '';
2620 # If we get here, we're creating a new cookie
2621 return undef unless defined($name) && $name ne ''; # this is an error
2624 push(@param,'-name'=>$name);
2625 push(@param,'-value'=>$value);
2626 push(@param,'-domain'=>$domain) if $domain;
2627 push(@param,'-path'=>$path) if $path;
2628 push(@param,'-expires'=>$expires) if $expires;
2629 push(@param,'-secure'=>$secure) if $secure;
2631 return new CGI::Cookie(@param);
2635 'parse_keywordlist' => <<'END_OF_FUNC',
2636 sub parse_keywordlist {
2637 my($self,$tosplit) = @_;
2638 $tosplit = unescape($tosplit); # unescape the keywords
2639 $tosplit=~tr/+/ /; # pluses to spaces
2640 my(@keywords) = split(/\s+/,$tosplit);
2645 'param_fetch' => <<'END_OF_FUNC',
2647 my($self,@p) = self_or_default(@_);
2648 my($name) = rearrange([NAME],@p);
2649 unless (exists($self->{$name})) {
2650 $self->add_parameter($name);
2651 $self->{$name} = [];
2654 return $self->{$name};
2658 ###############################################
2659 # OTHER INFORMATION PROVIDED BY THE ENVIRONMENT
2660 ###############################################
2662 #### Method: path_info
2663 # Return the extra virtual path information provided
2664 # after the URL (if any)
2666 'path_info' => <<'END_OF_FUNC',
2668 my ($self,$info) = self_or_default(@_);
2669 if (defined($info)) {
2670 $info = "/$info" if $info ne '' && substr($info,0,1) ne '/';
2671 $self->{'.path_info'} = $info;
2672 } elsif (! defined($self->{'.path_info'}) ) {
2673 $self->{'.path_info'} = defined($ENV{'PATH_INFO'}) ?
2674 $ENV{'PATH_INFO'} : '';
2676 # hack to fix broken path info in IIS
2677 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E// if $IIS;
2680 return $self->{'.path_info'};
2685 #### Method: request_method
2686 # Returns 'POST', 'GET', 'PUT' or 'HEAD'
2688 'request_method' => <<'END_OF_FUNC',
2689 sub request_method {
2690 return $ENV{'REQUEST_METHOD'};
2694 #### Method: content_type
2695 # Returns the content_type string
2697 'content_type' => <<'END_OF_FUNC',
2699 return $ENV{'CONTENT_TYPE'};
2703 #### Method: path_translated
2704 # Return the physical path information provided
2705 # by the URL (if any)
2707 'path_translated' => <<'END_OF_FUNC',
2708 sub path_translated {
2709 return $ENV{'PATH_TRANSLATED'};
2714 #### Method: query_string
2715 # Synthesize a query string from our current
2718 'query_string' => <<'END_OF_FUNC',
2720 my($self) = self_or_default(@_);
2721 my($param,$value,@pairs);
2722 foreach $param ($self->param) {
2723 my($eparam) = escape($param);
2724 foreach $value ($self->param($param)) {
2725 $value = escape($value);
2726 next unless defined $value;
2727 push(@pairs,"$eparam=$value");
2730 foreach (keys %{$self->{'.fieldnames'}}) {
2731 push(@pairs,".cgifields=".escape("$_"));
2733 return join($USE_PARAM_SEMICOLONS ? ';' : '&',@pairs);
2739 # Without parameters, returns an array of the
2740 # MIME types the browser accepts.
2741 # With a single parameter equal to a MIME
2742 # type, will return undef if the browser won't
2743 # accept it, 1 if the browser accepts it but
2744 # doesn't give a preference, or a floating point
2745 # value between 0.0 and 1.0 if the browser
2746 # declares a quantitative score for it.
2747 # This handles MIME type globs correctly.
2749 'Accept' => <<'END_OF_FUNC',
2751 my($self,$search) = self_or_CGI(@_);
2752 my(%prefs,$type,$pref,$pat);
2754 my(@accept) = split(',',$self->http('accept'));
2757 ($pref) = /q=(\d\.\d+|\d+)/;
2758 ($type) = m#(\S+/[^;]+)#;
2760 $prefs{$type}=$pref || 1;
2763 return keys %prefs unless $search;
2765 # if a search type is provided, we may need to
2766 # perform a pattern matching operation.
2767 # The MIME types use a glob mechanism, which
2768 # is easily translated into a perl pattern match
2770 # First return the preference for directly supported
2772 return $prefs{$search} if $prefs{$search};
2774 # Didn't get it, so try pattern matching.
2775 foreach (keys %prefs) {
2776 next unless /\*/; # not a pattern match
2777 ($pat = $_) =~ s/([^\w*])/\\$1/g; # escape meta characters
2778 $pat =~ s/\*/.*/g; # turn it into a pattern
2779 return $prefs{$_} if $search=~/$pat/;
2785 #### Method: user_agent
2786 # If called with no parameters, returns the user agent.
2787 # If called with one parameter, does a pattern match (case
2788 # insensitive) on the user agent.
2790 'user_agent' => <<'END_OF_FUNC',
2792 my($self,$match)=self_or_CGI(@_);
2793 return $self->http('user_agent') unless $match;
2794 return $self->http('user_agent') =~ /$match/i;
2799 #### Method: raw_cookie
2800 # Returns the magic cookies for the session.
2801 # The cookies are not parsed or altered in any way, i.e.
2802 # cookies are returned exactly as given in the HTTP
2803 # headers. If a cookie name is given, only that cookie's
2804 # value is returned, otherwise the entire raw cookie
2807 'raw_cookie' => <<'END_OF_FUNC',
2809 my($self,$key) = self_or_CGI(@_);
2811 require CGI::Cookie;
2813 if (defined($key)) {
2814 $self->{'.raw_cookies'} = CGI::Cookie->raw_fetch
2815 unless $self->{'.raw_cookies'};
2817 return () unless $self->{'.raw_cookies'};
2818 return () unless $self->{'.raw_cookies'}->{$key};
2819 return $self->{'.raw_cookies'}->{$key};
2821 return $self->http('cookie') || $ENV{'COOKIE'} || '';
2825 #### Method: virtual_host
2826 # Return the name of the virtual_host, which
2827 # is not always the same as the server
2829 'virtual_host' => <<'END_OF_FUNC',
2831 my $vh = http('host') || server_name();
2832 $vh =~ s/:\d+$//; # get rid of port number
2837 #### Method: remote_host
2838 # Return the name of the remote host, or its IP
2839 # address if unavailable. If this variable isn't
2840 # defined, it returns "localhost" for debugging
2843 'remote_host' => <<'END_OF_FUNC',
2845 return $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'}
2851 #### Method: remote_addr
2852 # Return the IP addr of the remote host.
2854 'remote_addr' => <<'END_OF_FUNC',
2856 return $ENV{'REMOTE_ADDR'} || '127.0.0.1';
2861 #### Method: script_name
2862 # Return the partial URL to this script for
2863 # self-referencing scripts. Also see
2864 # self_url(), which returns a URL with all state information
2867 'script_name' => <<'END_OF_FUNC',
2869 return $ENV{'SCRIPT_NAME'} if defined($ENV{'SCRIPT_NAME'});
2870 # These are for debugging
2871 return "/$0" unless $0=~/^\//;
2877 #### Method: referer
2878 # Return the HTTP_REFERER: useful for generating
2881 'referer' => <<'END_OF_FUNC',
2883 my($self) = self_or_CGI(@_);
2884 return $self->http('referer');
2889 #### Method: server_name
2890 # Return the name of the server
2892 'server_name' => <<'END_OF_FUNC',
2894 return $ENV{'SERVER_NAME'} || 'localhost';
2898 #### Method: server_software
2899 # Return the name of the server software
2901 'server_software' => <<'END_OF_FUNC',
2902 sub server_software {
2903 return $ENV{'SERVER_SOFTWARE'} || 'cmdline';
2907 #### Method: virtual_port
2908 # Return the server port, taking virtual hosts into account
2910 'virtual_port' => <<'END_OF_FUNC',
2912 my($self) = self_or_default(@_);
2913 my $vh = $self->http('host');
2915 return ($vh =~ /:(\d+)$/)[0] || '80';
2917 return $self->server_port();
2922 #### Method: server_port
2923 # Return the tcp/ip port the server is running on
2925 'server_port' => <<'END_OF_FUNC',
2927 return $ENV{'SERVER_PORT'} || 80; # for debugging
2931 #### Method: server_protocol
2932 # Return the protocol (usually HTTP/1.0)
2934 'server_protocol' => <<'END_OF_FUNC',
2935 sub server_protocol {
2936 return $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0'; # for debugging
2941 # Return the value of an HTTP variable, or
2942 # the list of variables if none provided
2944 'http' => <<'END_OF_FUNC',
2946 my ($self,$parameter) = self_or_CGI(@_);
2947 return $ENV{$parameter} if $parameter=~/^HTTP/;
2948 $parameter =~ tr/-/_/;
2949 return $ENV{"HTTP_\U$parameter\E"} if $parameter;
2951 foreach (keys %ENV) {
2952 push(@p,$_) if /^HTTP/;
2959 # Return the value of HTTPS
2961 'https' => <<'END_OF_FUNC',
2964 my ($self,$parameter) = self_or_CGI(@_);
2965 return $ENV{HTTPS} unless $parameter;
2966 return $ENV{$parameter} if $parameter=~/^HTTPS/;
2967 $parameter =~ tr/-/_/;
2968 return $ENV{"HTTPS_\U$parameter\E"} if $parameter;
2970 foreach (keys %ENV) {
2971 push(@p,$_) if /^HTTPS/;
2977 #### Method: protocol
2978 # Return the protocol (http or https currently)
2980 'protocol' => <<'END_OF_FUNC',
2984 return 'https' if uc($self->https()) eq 'ON';
2985 return 'https' if $self->server_port == 443;
2986 my $prot = $self->server_protocol;
2987 my($protocol,$version) = split('/',$prot);
2988 return "\L$protocol\E";
2992 #### Method: remote_ident
2993 # Return the identity of the remote user
2994 # (but only if his host is running identd)
2996 'remote_ident' => <<'END_OF_FUNC',
2998 return $ENV{'REMOTE_IDENT'};
3003 #### Method: auth_type
3004 # Return the type of use verification/authorization in use, if any.
3006 'auth_type' => <<'END_OF_FUNC',
3008 return $ENV{'AUTH_TYPE'};
3013 #### Method: remote_user
3014 # Return the authorization name used for user
3017 'remote_user' => <<'END_OF_FUNC',
3019 return $ENV{'REMOTE_USER'};
3024 #### Method: user_name
3025 # Try to return the remote user's name by hook or by
3028 'user_name' => <<'END_OF_FUNC',
3030 my ($self) = self_or_CGI(@_);
3031 return $self->http('from') || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
3035 #### Method: nosticky
3036 # Set or return the NOSTICKY global flag
3038 'nosticky' => <<'END_OF_FUNC',
3040 my ($self,$param) = self_or_CGI(@_);
3041 $CGI::NOSTICKY = $param if defined($param);
3042 return $CGI::NOSTICKY;
3047 # Set or return the NPH global flag
3049 'nph' => <<'END_OF_FUNC',
3051 my ($self,$param) = self_or_CGI(@_);
3052 $CGI::NPH = $param if defined($param);
3057 #### Method: private_tempfiles
3058 # Set or return the private_tempfiles global flag
3060 'private_tempfiles' => <<'END_OF_FUNC',
3061 sub private_tempfiles {
3062 my ($self,$param) = self_or_CGI(@_);
3063 $CGI::PRIVATE_TEMPFILES = $param if defined($param);
3064 return $CGI::PRIVATE_TEMPFILES;
3067 #### Method: close_upload_files
3068 # Set or return the close_upload_files global flag
3070 'close_upload_files' => <<'END_OF_FUNC',
3071 sub close_upload_files {
3072 my ($self,$param) = self_or_CGI(@_);
3073 $CGI::CLOSE_UPLOAD_FILES = $param if defined($param);
3074 return $CGI::CLOSE_UPLOAD_FILES;
3079 #### Method: default_dtd
3080 # Set or return the default_dtd global
3082 'default_dtd' => <<'END_OF_FUNC',
3084 my ($self,$param,$param2) = self_or_CGI(@_);
3085 if (defined $param2 && defined $param) {
3086 $CGI::DEFAULT_DTD = [ $param, $param2 ];
3087 } elsif (defined $param) {
3088 $CGI::DEFAULT_DTD = $param;
3090 return $CGI::DEFAULT_DTD;
3094 # -------------- really private subroutines -----------------
3095 'previous_or_default' => <<'END_OF_FUNC',
3096 sub previous_or_default {
3097 my($self,$name,$defaults,$override) = @_;
3100 if (!$override && ($self->{'.fieldnames'}->{$name} ||
3101 defined($self->param($name)) ) ) {
3102 grep($selected{$_}++,$self->param($name));
3103 } elsif (defined($defaults) && ref($defaults) &&
3104 (ref($defaults) eq 'ARRAY')) {
3105 grep($selected{$_}++,@{$defaults});
3107 $selected{$defaults}++ if defined($defaults);
3114 'register_parameter' => <<'END_OF_FUNC',
3115 sub register_parameter {
3116 my($self,$param) = @_;
3117 $self->{'.parametersToAdd'}->{$param}++;
3121 'get_fields' => <<'END_OF_FUNC',
3124 return $self->CGI::hidden('-name'=>'.cgifields',
3125 '-values'=>[keys %{$self->{'.parametersToAdd'}}],
3130 'read_from_cmdline' => <<'END_OF_FUNC',
3131 sub read_from_cmdline {
3135 if ($DEBUG && @ARGV) {
3137 } elsif ($DEBUG > 1) {
3138 require "shellwords.pl";
3139 print STDERR "(offline mode: enter name=value pairs on standard input; press ^D or ^Z when done)\n";
3140 chomp(@lines = <STDIN>); # remove newlines
3141 $input = join(" ",@lines);
3142 @words = &shellwords($input);
3149 if ("@words"=~/=/) {
3150 $query_string = join('&',@words);
3152 $query_string = join('+',@words);
3154 if ($query_string =~ /^(.*?)\?(.*)$/)
3159 return { 'query_string' => $query_string, 'subpath' => $subpath };
3164 # subroutine: read_multipart
3166 # Read multipart data and store it into our parameters.
3167 # An interesting feature is that if any of the parts is a file, we
3168 # create a temporary file and open up a filehandle on it so that the
3169 # caller can read from it if necessary.
3171 'read_multipart' => <<'END_OF_FUNC',
3172 sub read_multipart {
3173 my($self,$boundary,$length) = @_;
3174 my($buffer) = $self->new_MultipartBuffer($boundary,$length);
3175 return unless $buffer;
3178 while (!$buffer->eof) {
3179 %header = $buffer->readHeader;
3182 $self->cgi_error("400 Bad request (malformed multipart POST)");
3186 my($param)= $header{'Content-Disposition'}=~/ name="?([^\";]*)"?/;
3189 # Bug: Netscape doesn't escape quotation marks in file names!!!
3190 my($filename) = $header{'Content-Disposition'}=~/ filename="?([^\"]*)"?/;
3191 # Test for Opera's multiple upload feature
3192 my($multipart) = ( defined( $header{'Content-Type'} ) &&
3193 $header{'Content-Type'} =~ /multipart\/mixed/ ) ?
3196 # add this parameter to our list
3197 $self->add_parameter($param);
3199 # If no filename specified, then just read the data and assign it
3200 # to our parameter list.
3201 if ( ( !defined($filename) || $filename eq '' ) && !$multipart ) {
3202 my($value) = $buffer->readBody;
3204 push(@{$self->{$param}},$value);
3208 my ($tmpfile,$tmp,$filehandle);
3210 # If we get here, then we are dealing with a potentially large
3211 # uploaded form. Save the data to a temporary file, then open
3212 # the file for reading.
3214 # skip the file if uploads disabled
3215 if ($DISABLE_UPLOADS) {
3216 while (defined($data = $buffer->read)) { }
3220 # set the filename to some recognizable value
3221 if ( ( !defined($filename) || $filename eq '' ) && $multipart ) {
3222 $filename = "multipart/mixed";
3225 # choose a relatively unpredictable tmpfile sequence number
3226 my $seqno = unpack("%16C*",join('',localtime,values %ENV));
3227 for (my $cnt=10;$cnt>0;$cnt--) {
3228 next unless $tmpfile = new CGITempFile($seqno);
3229 $tmp = $tmpfile->as_string;
3230 last if defined($filehandle = Fh->new($filename,$tmp,$PRIVATE_TEMPFILES));
3231 $seqno += int rand(100);
3233 die "CGI open of tmpfile: $!\n" unless defined $filehandle;
3234 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode
3235 && defined fileno($filehandle);
3237 # if this is an multipart/mixed attachment, save the header
3238 # together with the body for later parsing with an external
3239 # MIME parser module
3241 foreach ( keys %header ) {
3242 print $filehandle "$_: $header{$_}${CRLF}";
3244 print $filehandle "${CRLF}";
3250 while (defined($data = $buffer->read)) {
3251 if (defined $self->{'.upload_hook'})
3253 $totalbytes += length($data);
3254 &{$self->{'.upload_hook'}}($filename ,$data, $totalbytes, $self->{'.upload_data'});
3256 print $filehandle $data;
3259 # back up to beginning of file
3260 seek($filehandle,0,0);
3262 ## Close the filehandle if requested this allows a multipart MIME
3263 ## upload to contain many files, and we won't die due to too many
3264 ## open file handles. The user can access the files using the hash
3266 close $filehandle if $CLOSE_UPLOAD_FILES;
3267 $CGI::DefaultClass->binmode($filehandle) if $CGI::needs_binmode;
3269 # Save some information about the uploaded file where we can get
3271 $self->{'.tmpfiles'}->{fileno($filehandle)}= {
3272 hndl => $filehandle,
3276 push(@{$self->{$param}},$filehandle);
3282 'upload' =><<'END_OF_FUNC',
3284 my($self,$param_name) = self_or_default(@_);
3285 my @param = grep(ref && fileno($_), $self->param($param_name));
3286 return unless @param;
3287 return wantarray ? @param : $param[0];
3291 'tmpFileName' => <<'END_OF_FUNC',
3293 my($self,$filename) = self_or_default(@_);
3294 return $self->{'.tmpfiles'}->{fileno($filename)}->{name} ?
3295 $self->{'.tmpfiles'}->{fileno($filename)}->{name}->as_string
3300 'uploadInfo' => <<'END_OF_FUNC',
3302 my($self,$filename) = self_or_default(@_);
3303 return $self->{'.tmpfiles'}->{fileno($filename)}->{info};
3307 # internal routine, don't use
3308 '_set_values_and_labels' => <<'END_OF_FUNC',
3309 sub _set_values_and_labels {
3312 $$l = $v if ref($v) eq 'HASH' && !ref($$l);
3313 return $self->param($n) if !defined($v);
3314 return $v if !ref($v);
3315 return ref($v) eq 'HASH' ? keys %$v : @$v;
3319 # internal routine, don't use
3320 '_set_attributes' => <<'END_OF_FUNC',
3321 sub _set_attributes {
3323 my($element, $attributes) = @_;
3324 return '' unless defined($attributes->{$element});
3326 foreach my $attrib (keys %{$attributes->{$element}}) {
3328 $attribs .= "@{[lc($attrib)]}=\"$attributes->{$element}{$attrib}\" ";
3335 '_compile_all' => <<'END_OF_FUNC',
3338 next if defined(&$_);
3339 $AUTOLOAD = "CGI::$_";
3349 #########################################################
3350 # Globals and stubs for other packages that we use.
3351 #########################################################
3353 ################### Fh -- lightweight filehandle ###############
3362 *Fh::AUTOLOAD = \&CGI::AUTOLOAD;
3364 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3365 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3367 'asString' => <<'END_OF_FUNC',
3370 # get rid of package name
3371 (my $i = $$self) =~ s/^\*(\w+::fh\d{5})+//;
3372 $i =~ s/%(..)/ chr(hex($1)) /eg;
3373 return $i.$CGI::TAINTED;
3375 # This was an extremely clever patch that allowed "use strict refs".
3376 # Unfortunately it relied on another bug that caused leaky file descriptors.
3377 # The underlying bug has been fixed, so this no longer works. However
3378 # "strict refs" still works for some reason.
3380 # return ${*{$self}{SCALAR}};
3385 'compare' => <<'END_OF_FUNC',
3389 return "$self" cmp $value;
3393 'new' => <<'END_OF_FUNC',
3395 my($pack,$name,$file,$delete) = @_;
3396 _setup_symbols(@SAVED_SYMBOLS) if @SAVED_SYMBOLS;
3397 require Fcntl unless defined &Fcntl::O_RDWR;
3398 (my $safename = $name) =~ s/([':%])/ sprintf '%%%02X', ord $1 /eg;
3399 my $fv = ++$FH . $safename;
3400 my $ref = \*{"Fh::$fv"};
3401 $file =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3403 sysopen($ref,$safe,Fcntl::O_RDWR()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600) || return;
3404 unlink($safe) if $delete;
3405 CORE::delete $Fh::{$fv};
3406 return bless $ref,$pack;
3410 'DESTROY' => <<'END_OF_FUNC',
3420 ######################## MultipartBuffer ####################
3421 package MultipartBuffer;
3423 use constant DEBUG => 0;
3425 # how many bytes to read at a time. We use
3426 # a 4K buffer by default.
3427 $INITIAL_FILLUNIT = 1024 * 4;
3428 $TIMEOUT = 240*60; # 4 hour timeout for big files
3429 $SPIN_LOOP_MAX = 2000; # bug fix for some Netscape servers
3432 #reuse the autoload function
3433 *MultipartBuffer::AUTOLOAD = \&CGI::AUTOLOAD;
3435 # avoid autoloader warnings
3438 ###############################################################################
3439 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3440 ###############################################################################
3441 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3442 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3445 'new' => <<'END_OF_FUNC',
3447 my($package,$interface,$boundary,$length) = @_;
3448 $FILLUNIT = $INITIAL_FILLUNIT;
3449 $CGI::DefaultClass->binmode($IN); # if $CGI::needs_binmode; # just do it always
3451 # If the user types garbage into the file upload field,
3452 # then Netscape passes NOTHING to the server (not good).
3453 # We may hang on this read in that case. So we implement
3454 # a read timeout. If nothing is ready to read
3455 # by then, we return.
3457 # Netscape seems to be a little bit unreliable
3458 # about providing boundary strings.
3459 my $boundary_read = 0;
3462 # Under the MIME spec, the boundary consists of the
3463 # characters "--" PLUS the Boundary string
3465 # BUG: IE 3.01 on the Macintosh uses just the boundary -- not
3466 # the two extra hyphens. We do a special case here on the user-agent!!!!
3467 $boundary = "--$boundary" unless CGI::user_agent('MSIE\s+3\.0[12];\s*Mac|DreamPassport');
3469 } else { # otherwise we find it ourselves
3471 ($old,$/) = ($/,$CRLF); # read a CRLF-delimited line
3472 $boundary = <STDIN>; # BUG: This won't work correctly under mod_perl
3473 $length -= length($boundary);
3474 chomp($boundary); # remove the CRLF
3475 $/ = $old; # restore old line separator
3479 my $self = {LENGTH=>$length,
3480 BOUNDARY=>$boundary,
3481 INTERFACE=>$interface,
3485 $FILLUNIT = length($boundary)
3486 if length($boundary) > $FILLUNIT;
3488 my $retval = bless $self,ref $package || $package;
3490 # Read the preamble and the topmost (boundary) line plus the CRLF.
3491 unless ($boundary_read) {
3492 while ($self->read(0)) { }
3494 die "Malformed multipart POST: data truncated\n" if $self->eof;
3500 'readHeader' => <<'END_OF_FUNC',
3507 local($CRLF) = "\015\012" if $CGI::OS eq 'VMS' || $CGI::EBCDIC;
3510 $self->fillBuffer($FILLUNIT);
3511 $ok++ if ($end = index($self->{BUFFER},"${CRLF}${CRLF}")) >= 0;
3512 $ok++ if $self->{BUFFER} eq '';
3513 $bad++ if !$ok && $self->{LENGTH} <= 0;
3514 # this was a bad idea
3515 # $FILLUNIT *= 2 if length($self->{BUFFER}) >= $FILLUNIT;
3516 } until $ok || $bad;
3519 #EBCDIC NOTE: translate header into EBCDIC, but watch out for continuation lines!
3521 my($header) = substr($self->{BUFFER},0,$end+2);
3522 substr($self->{BUFFER},0,$end+4) = '';
3526 warn "untranslated header=$header\n" if DEBUG;
3527 $header = CGI::Util::ascii2ebcdic($header);
3528 warn "translated header=$header\n" if DEBUG;
3531 # See RFC 2045 Appendix A and RFC 822 sections 3.4.8
3532 # (Folding Long Header Fields), 3.4.3 (Comments)
3533 # and 3.4.5 (Quoted-Strings).
3535 my $token = '[-\w!\#$%&\'*+.^_\`|{}~]';
3536 $header=~s/$CRLF\s+/ /og; # merge continuation lines
3538 while ($header=~/($token+):\s+([^$CRLF]*)/mgox) {
3539 my ($field_name,$field_value) = ($1,$2);
3540 $field_name =~ s/\b(\w)/uc($1)/eg; #canonicalize
3541 $return{$field_name}=$field_value;
3547 # This reads and returns the body as a single scalar value.
3548 'readBody' => <<'END_OF_FUNC',
3554 #EBCDIC NOTE: want to translate returnval into EBCDIC HERE
3556 while (defined($data = $self->read)) {
3557 $returnval .= $data;
3561 warn "untranslated body=$returnval\n" if DEBUG;
3562 $returnval = CGI::Util::ascii2ebcdic($returnval);
3563 warn "translated body=$returnval\n" if DEBUG;
3569 # This will read $bytes or until the boundary is hit, whichever happens
3570 # first. After the boundary is hit, we return undef. The next read will
3571 # skip over the boundary and begin reading again;
3572 'read' => <<'END_OF_FUNC',
3574 my($self,$bytes) = @_;
3576 # default number of bytes to read
3577 $bytes = $bytes || $FILLUNIT;
3579 # Fill up our internal buffer in such a way that the boundary
3580 # is never split between reads.
3581 $self->fillBuffer($bytes);
3583 my $boundary_start = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}) : $self->{BOUNDARY};
3584 my $boundary_end = $CGI::EBCDIC ? CGI::Util::ebcdic2ascii($self->{BOUNDARY}.'--') : $self->{BOUNDARY}.'--';
3586 # Find the boundary in the buffer (it may not be there).
3587 my $start = index($self->{BUFFER},$boundary_start);
3589 warn "boundary=$self->{BOUNDARY} length=$self->{LENGTH} start=$start\n" if DEBUG;
3590 # protect against malformed multipart POST operations
3591 die "Malformed multipart POST\n" unless ($start >= 0) || ($self->{LENGTH} > 0);
3594 #EBCDIC NOTE: want to translate boundary search into ASCII here.
3596 # If the boundary begins the data, then skip past it
3600 # clear us out completely if we've hit the last boundary.
3601 if (index($self->{BUFFER},$boundary_end)==0) {
3607 # just remove the boundary.
3608 substr($self->{BUFFER},0,length($boundary_start))='';
3609 $self->{BUFFER} =~ s/^\012\015?//;
3614 if ($start > 0) { # read up to the boundary
3615 $bytesToReturn = $start-2 > $bytes ? $bytes : $start;
3616 } else { # read the requested number of bytes
3617 # leave enough bytes in the buffer to allow us to read
3618 # the boundary. Thanks to Kevin Hendrick for finding
3620 $bytesToReturn = $bytes - (length($boundary_start)+1);
3623 my $returnval=substr($self->{BUFFER},0,$bytesToReturn);
3624 substr($self->{BUFFER},0,$bytesToReturn)='';
3626 # If we hit the boundary, remove the CRLF from the end.
3627 return ($bytesToReturn==$start)
3628 ? substr($returnval,0,-2) : $returnval;
3633 # This fills up our internal buffer in such a way that the
3634 # boundary is never split between reads
3635 'fillBuffer' => <<'END_OF_FUNC',
3637 my($self,$bytes) = @_;
3638 return unless $self->{LENGTH};
3640 my($boundaryLength) = length($self->{BOUNDARY});
3641 my($bufferLength) = length($self->{BUFFER});
3642 my($bytesToRead) = $bytes - $bufferLength + $boundaryLength + 2;
3643 $bytesToRead = $self->{LENGTH} if $self->{LENGTH} < $bytesToRead;
3645 # Try to read some data. We may hang here if the browser is screwed up.
3646 my $bytesRead = $self->{INTERFACE}->read_from_client(\$self->{BUFFER},
3649 warn "bytesToRead=$bytesToRead, bufferLength=$bufferLength, buffer=$self->{BUFFER}\n" if DEBUG;
3650 $self->{BUFFER} = '' unless defined $self->{BUFFER};
3652 # An apparent bug in the Apache server causes the read()
3653 # to return zero bytes repeatedly without blocking if the
3654 # remote user aborts during a file transfer. I don't know how
3655 # they manage this, but the workaround is to abort if we get
3656 # more than SPIN_LOOP_MAX consecutive zero reads.
3657 if ($bytesRead == 0) {
3658 die "CGI.pm: Server closed socket during multipart read (client aborted?).\n"
3659 if ($self->{ZERO_LOOP_COUNTER}++ >= $SPIN_LOOP_MAX);
3661 $self->{ZERO_LOOP_COUNTER}=0;
3664 $self->{LENGTH} -= $bytesRead;
3669 # Return true when we've finished reading
3670 'eof' => <<'END_OF_FUNC'
3673 return 1 if (length($self->{BUFFER}) == 0)
3674 && ($self->{LENGTH} <= 0);
3682 ####################################################################################
3683 ################################## TEMPORARY FILES #################################
3684 ####################################################################################
3685 package CGITempFile;
3688 undef $TMPDIRECTORY;
3690 $MAC = $CGI::OS eq 'MACINTOSH';
3691 my ($vol) = $MAC ? MacPerl::Volumes() =~ /:(.*)/ : "";
3692 unless ($TMPDIRECTORY) {
3693 @TEMP=("${SL}usr${SL}tmp","${SL}var${SL}tmp",
3694 "C:${SL}temp","${SL}tmp","${SL}temp",
3695 "${vol}${SL}Temporary Items",
3696 "${SL}WWW_ROOT", "${SL}SYS\$SCRATCH",
3697 "C:${SL}system${SL}temp");
3698 unshift(@TEMP,$ENV{'TMPDIR'}) if defined $ENV{'TMPDIR'};
3700 # this feature was supposed to provide per-user tmpfiles, but
3701 # it is problematic.
3702 # unshift(@TEMP,(getpwuid($<))[7].'/tmp') if $CGI::OS eq 'UNIX';
3703 # Rob: getpwuid() is unfortunately UNIX specific. On brain dead OS'es this
3704 # : can generate a 'getpwuid() not implemented' exception, even though
3705 # : it's never called. Found under DOS/Win with the DJGPP perl port.
3706 # : Refer to getpwuid() only at run-time if we're fortunate and have UNIX.
3707 # unshift(@TEMP,(eval {(getpwuid($>))[7]}).'/tmp') if $CGI::OS eq 'UNIX' and $> != 0;
3710 do {$TMPDIRECTORY = $_; last} if -d $_ && -w _;
3713 $TMPDIRECTORY = $MAC ? "" : "." unless $TMPDIRECTORY;
3720 # cute feature, but overload implementation broke it
3721 # %OVERLOAD = ('""'=>'as_string');
3722 *CGITempFile::AUTOLOAD = \&CGI::AUTOLOAD;
3726 $$self =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$! || return;
3727 my $safe = $1; # untaint operation
3728 unlink $safe; # get rid of the file
3731 ###############################################################################
3732 ################# THESE FUNCTIONS ARE AUTOLOADED ON DEMAND ####################
3733 ###############################################################################
3734 $AUTOLOADED_ROUTINES = ''; # prevent -w error
3735 $AUTOLOADED_ROUTINES=<<'END_OF_AUTOLOAD';
3738 'new' => <<'END_OF_FUNC',
3740 my($package,$sequence) = @_;
3742 find_tempdir() unless -w $TMPDIRECTORY;
3743 for (my $i = 0; $i < $MAXTRIES; $i++) {
3744 last if ! -f ($filename = sprintf("${TMPDIRECTORY}${SL}CGItemp%d",$sequence++));
3746 # check that it is a more-or-less valid filename
3747 return unless $filename =~ m!^([a-zA-Z0-9_ \'\":/.\$\\-]+)$!;
3748 # this used to untaint, now it doesn't
3750 return bless \$filename;
3754 'as_string' => <<'END_OF_FUNC'
3766 # We get a whole bunch of warnings about "possibly uninitialized variables"
3767 # when running with the -w switch. Touch them all once to get rid of the
3768 # warnings. This is ugly and I hate it.
3773 $MultipartBuffer::SPIN_LOOP_MAX;
3774 $MultipartBuffer::CRLF;
3775 $MultipartBuffer::TIMEOUT;
3776 $MultipartBuffer::INITIAL_FILLUNIT;
3787 CGI - Simple Common Gateway Interface Class
3791 # CGI script that creates a fill-out form
3792 # and echoes back its values.
3794 use CGI qw/:standard/;
3796 start_html('A Simple Example'),
3797 h1('A Simple Example'),
3799 "What's your name? ",textfield('name'),p,
3800 "What's the combination?", p,
3801 checkbox_group(-name=>'words',
3802 -values=>['eenie','meenie','minie','moe'],
3803 -defaults=>['eenie','minie']), p,
3804 "What's your favorite color? ",
3805 popup_menu(-name=>'color',
3806 -values=>['red','green','blue','chartreuse']),p,
3812 print "Your name is",em(param('name')),p,
3813 "The keywords are: ",em(join(", ",param('words'))),p,
3814 "Your favorite color is ",em(param('color')),
3820 This perl library uses perl5 objects to make it easy to create Web
3821 fill-out forms and parse their contents. This package defines CGI
3822 objects, entities that contain the values of the current query string
3823 and other state variables. Using a CGI object's methods, you can
3824 examine keywords and parameters passed to your script, and create
3825 forms whose initial values are taken from the current query (thereby
3826 preserving state information). The module provides shortcut functions
3827 that produce boilerplate HTML, reducing typing and coding errors. It
3828 also provides functionality for some of the more advanced features of
3829 CGI scripting, including support for file uploads, cookies, cascading
3830 style sheets, server push, and frames.
3832 CGI.pm also provides a simple function-oriented programming style for
3833 those who don't need its object-oriented features.
3835 The current version of CGI.pm is available at
3837 http://www.genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
3838 ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
3842 =head2 PROGRAMMING STYLE
3844 There are two styles of programming with CGI.pm, an object-oriented
3845 style and a function-oriented style. In the object-oriented style you
3846 create one or more CGI objects and then use object methods to create
3847 the various elements of the page. Each CGI object starts out with the
3848 list of named parameters that were passed to your CGI script by the
3849 server. You can modify the objects, save them to a file or database
3850 and recreate them. Because each object corresponds to the "state" of
3851 the CGI script, and because each object's parameter list is
3852 independent of the others, this allows you to save the state of the
3853 script and restore it later.
3855 For example, using the object oriented style, here is how you create
3856 a simple "Hello World" HTML page:
3858 #!/usr/local/bin/perl -w
3859 use CGI; # load CGI routines
3860 $q = new CGI; # create new CGI object
3861 print $q->header, # create the HTTP header
3862 $q->start_html('hello world'), # start the HTML
3863 $q->h1('hello world'), # level 1 header
3864 $q->end_html; # end the HTML
3866 In the function-oriented style, there is one default CGI object that
3867 you rarely deal with directly. Instead you just call functions to
3868 retrieve CGI parameters, create HTML tags, manage cookies, and so
3869 on. This provides you with a cleaner programming interface, but
3870 limits you to using one CGI object at a time. The following example
3871 prints the same page, but uses the function-oriented interface.
3872 The main differences are that we now need to import a set of functions
3873 into our name space (usually the "standard" functions), and we don't
3874 need to create the CGI object.
3876 #!/usr/local/bin/perl
3877 use CGI qw/:standard/; # load standard CGI routines
3878 print header, # create the HTTP header
3879 start_html('hello world'), # start the HTML
3880 h1('hello world'), # level 1 header
3881 end_html; # end the HTML
3883 The examples in this document mainly use the object-oriented style.
3884 See HOW TO IMPORT FUNCTIONS for important information on
3885 function-oriented programming in CGI.pm
3887 =head2 CALLING CGI.PM ROUTINES
3889 Most CGI.pm routines accept several arguments, sometimes as many as 20
3890 optional ones! To simplify this interface, all routines use a named
3891 argument calling style that looks like this:
3893 print $q->header(-type=>'image/gif',-expires=>'+3d');
3895 Each argument name is preceded by a dash. Neither case nor order
3896 matters in the argument list. -type, -Type, and -TYPE are all
3897 acceptable. In fact, only the first argument needs to begin with a
3898 dash. If a dash is present in the first argument, CGI.pm assumes
3899 dashes for the subsequent ones.
3901 Several routines are commonly called with just one argument. In the
3902 case of these routines you can provide the single argument without an
3903 argument name. header() happens to be one of these routines. In this
3904 case, the single argument is the document type.
3906 print $q->header('text/html');
3908 Other such routines are documented below.
3910 Sometimes named arguments expect a scalar, sometimes a reference to an
3911 array, and sometimes a reference to a hash. Often, you can pass any
3912 type of argument and the routine will do whatever is most appropriate.
3913 For example, the param() routine is used to set a CGI parameter to a
3914 single or a multi-valued value. The two cases are shown below:
3916 $q->param(-name=>'veggie',-value=>'tomato');
3917 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
3919 A large number of routines in CGI.pm actually aren't specifically
3920 defined in the module, but are generated automatically as needed.
3921 These are the "HTML shortcuts," routines that generate HTML tags for
3922 use in dynamically-generated pages. HTML tags have both attributes
3923 (the attribute="value" pairs within the tag itself) and contents (the
3924 part between the opening and closing pairs.) To distinguish between
3925 attributes and contents, CGI.pm uses the convention of passing HTML
3926 attributes as a hash reference as the first argument, and the
3927 contents, if any, as any subsequent arguments. It works out like
3933 h1('some','contents'); <h1>some contents</h1>
3934 h1({-align=>left}); <h1 align="LEFT">
3935 h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
3937 HTML tags are described in more detail later.
3939 Many newcomers to CGI.pm are puzzled by the difference between the
3940 calling conventions for the HTML shortcuts, which require curly braces
3941 around the HTML tag attributes, and the calling conventions for other
3942 routines, which manage to generate attributes without the curly
3943 brackets. Don't be confused. As a convenience the curly braces are
3944 optional in all but the HTML shortcuts. If you like, you can use
3945 curly braces when calling any routine that takes named arguments. For
3948 print $q->header( {-type=>'image/gif',-expires=>'+3d'} );
3950 If you use the B<-w> switch, you will be warned that some CGI.pm argument
3951 names conflict with built-in Perl functions. The most frequent of
3952 these is the -values argument, used to create multi-valued menus,
3953 radio button clusters and the like. To get around this warning, you
3954 have several choices:
3960 Use another name for the argument, if one is available.
3961 For example, -value is an alias for -values.
3965 Change the capitalization, e.g. -Values
3969 Put quotes around the argument name, e.g. '-values'
3973 Many routines will do something useful with a named argument that it
3974 doesn't recognize. For example, you can produce non-standard HTTP
3975 header fields by providing them as named arguments:
3977 print $q->header(-type => 'text/html',
3978 -cost => 'Three smackers',
3979 -annoyance_level => 'high',
3980 -complaints_to => 'bit bucket');
3982 This will produce the following nonstandard HTTP header:
3985 Cost: Three smackers
3986 Annoyance-level: high
3987 Complaints-to: bit bucket
3988 Content-type: text/html
3990 Notice the way that underscores are translated automatically into
3991 hyphens. HTML-generating routines perform a different type of
3994 This feature allows you to keep up with the rapidly changing HTTP and
3997 =head2 CREATING A NEW QUERY OBJECT (OBJECT-ORIENTED STYLE):
4001 This will parse the input (from both POST and GET methods) and store
4002 it into a perl5 object called $query.
4004 =head2 CREATING A NEW QUERY OBJECT FROM AN INPUT FILE
4006 $query = new CGI(INPUTFILE);
4008 If you provide a file handle to the new() method, it will read
4009 parameters from the file (or STDIN, or whatever). The file can be in
4010 any of the forms describing below under debugging (i.e. a series of
4011 newline delimited TAG=VALUE pairs will work). Conveniently, this type
4012 of file is created by the save() method (see below). Multiple records
4013 can be saved and restored.
4015 Perl purists will be pleased to know that this syntax accepts
4016 references to file handles, or even references to filehandle globs,
4017 which is the "official" way to pass a filehandle:
4019 $query = new CGI(\*STDIN);
4021 You can also initialize the CGI object with a FileHandle or IO::File
4024 If you are using the function-oriented interface and want to
4025 initialize CGI state from a file handle, the way to do this is with
4026 B<restore_parameters()>. This will (re)initialize the
4027 default CGI object from the indicated file handle.
4029 open (IN,"test.in") || die;
4030 restore_parameters(IN);
4033 You can also initialize the query object from an associative array
4036 $query = new CGI( {'dinosaur'=>'barney',
4037 'song'=>'I love you',
4038 'friends'=>[qw/Jessica George Nancy/]}
4041 or from a properly formatted, URL-escaped query string:
4043 $query = new CGI('dinosaur=barney&color=purple');
4045 or from a previously existing CGI object (currently this clones the
4046 parameter list, but none of the other object-specific fields, such as
4049 $old_query = new CGI;
4050 $new_query = new CGI($old_query);
4052 To create an empty query, initialize it from an empty string or hash:
4054 $empty_query = new CGI("");
4058 $empty_query = new CGI({});
4060 =head2 FETCHING A LIST OF KEYWORDS FROM THE QUERY:
4062 @keywords = $query->keywords
4064 If the script was invoked as the result of an <ISINDEX> search, the
4065 parsed keywords can be obtained as an array using the keywords() method.
4067 =head2 FETCHING THE NAMES OF ALL THE PARAMETERS PASSED TO YOUR SCRIPT:
4069 @names = $query->param
4071 If the script was invoked with a parameter list
4072 (e.g. "name1=value1&name2=value2&name3=value3"), the param() method
4073 will return the parameter names as a list. If the script was invoked
4074 as an <ISINDEX> script and contains a string without ampersands
4075 (e.g. "value1+value2+value3") , there will be a single parameter named
4076 "keywords" containing the "+"-delimited keywords.
4078 NOTE: As of version 1.5, the array of parameter names returned will
4079 be in the same order as they were submitted by the browser.
4080 Usually this order is the same as the order in which the
4081 parameters are defined in the form (however, this isn't part
4082 of the spec, and so isn't guaranteed).
4084 =head2 FETCHING THE VALUE OR VALUES OF A SINGLE NAMED PARAMETER:
4086 @values = $query->param('foo');
4090 $value = $query->param('foo');
4092 Pass the param() method a single argument to fetch the value of the
4093 named parameter. If the parameter is multivalued (e.g. from multiple
4094 selections in a scrolling list), you can ask to receive an array. Otherwise
4095 the method will return a single value.
4097 If a value is not given in the query string, as in the queries
4098 "name1=&name2=" or "name1&name2", it will be returned as an empty
4099 string. This feature is new in 2.63.
4102 If the parameter does not exist at all, then param() will return undef
4103 in a scalar context, and the empty list in a list context.
4106 =head2 SETTING THE VALUE(S) OF A NAMED PARAMETER:
4108 $query->param('foo','an','array','of','values');
4110 This sets the value for the named parameter 'foo' to an array of
4111 values. This is one way to change the value of a field AFTER
4112 the script has been invoked once before. (Another way is with
4113 the -override parameter accepted by all methods that generate
4116 param() also recognizes a named parameter style of calling described
4117 in more detail later:
4119 $query->param(-name=>'foo',-values=>['an','array','of','values']);
4123 $query->param(-name=>'foo',-value=>'the value');
4125 =head2 APPENDING ADDITIONAL VALUES TO A NAMED PARAMETER:
4127 $query->append(-name=>'foo',-values=>['yet','more','values']);
4129 This adds a value or list of values to the named parameter. The
4130 values are appended to the end of the parameter if it already exists.
4131 Otherwise the parameter is created. Note that this method only
4132 recognizes the named argument calling syntax.
4134 =head2 IMPORTING ALL PARAMETERS INTO A NAMESPACE:
4136 $query->import_names('R');
4138 This creates a series of variables in the 'R' namespace. For example,
4139 $R::foo, @R:foo. For keyword lists, a variable @R::keywords will appear.
4140 If no namespace is given, this method will assume 'Q'.
4141 WARNING: don't import anything into 'main'; this is a major security
4144 NOTE 1: Variable names are transformed as necessary into legal Perl
4145 variable names. All non-legal characters are transformed into
4146 underscores. If you need to keep the original names, you should use
4147 the param() method instead to access CGI variables by name.
4149 NOTE 2: In older versions, this method was called B<import()>. As of version 2.20,
4150 this name has been removed completely to avoid conflict with the built-in
4151 Perl module B<import> operator.
4153 =head2 DELETING A PARAMETER COMPLETELY:
4155 $query->delete('foo','bar','baz');
4157 This completely clears a list of parameters. It sometimes useful for
4158 resetting parameters that you don't want passed down between script
4161 If you are using the function call interface, use "Delete()" instead
4162 to avoid conflicts with Perl's built-in delete operator.
4164 =head2 DELETING ALL PARAMETERS:
4166 $query->delete_all();
4168 This clears the CGI object completely. It might be useful to ensure
4169 that all the defaults are taken when you create a fill-out form.
4171 Use Delete_all() instead if you are using the function call interface.
4173 =head2 DIRECT ACCESS TO THE PARAMETER LIST:
4175 $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
4176 unshift @{$q->param_fetch(-name=>'address')},'George Munster';
4178 If you need access to the parameter list in a way that isn't covered
4179 by the methods above, you can obtain a direct reference to it by
4180 calling the B<param_fetch()> method with the name of the . This
4181 will return an array reference to the named parameters, which you then
4182 can manipulate in any way you like.
4184 You can also use a named argument style using the B<-name> argument.
4186 =head2 FETCHING THE PARAMETER LIST AS A HASH:
4189 print $params->{'address'};
4190 @foo = split("\0",$params->{'foo'});
4196 Many people want to fetch the entire parameter list as a hash in which
4197 the keys are the names of the CGI parameters, and the values are the
4198 parameters' values. The Vars() method does this. Called in a scalar
4199 context, it returns the parameter list as a tied hash reference.
4200 Changing a key changes the value of the parameter in the underlying
4201 CGI parameter list. Called in a list context, it returns the
4202 parameter list as an ordinary hash. This allows you to read the
4203 contents of the parameter list, but not to change it.
4205 When using this, the thing you must watch out for are multivalued CGI
4206 parameters. Because a hash cannot distinguish between scalar and
4207 list context, multivalued parameters will be returned as a packed
4208 string, separated by the "\0" (null) character. You must split this
4209 packed string in order to get at the individual values. This is the
4210 convention introduced long ago by Steve Brenner in his cgi-lib.pl
4211 module for Perl version 4.
4213 If you wish to use Vars() as a function, import the I<:cgi-lib> set of
4214 function calls (also see the section on CGI-LIB compatibility).
4216 =head2 SAVING THE STATE OF THE SCRIPT TO A FILE:
4218 $query->save(FILEHANDLE)
4220 This will write the current state of the form to the provided
4221 filehandle. You can read it back in by providing a filehandle
4222 to the new() method. Note that the filehandle can be a file, a pipe,
4225 The format of the saved file is:
4233 Both name and value are URL escaped. Multi-valued CGI parameters are
4234 represented as repeated names. A session record is delimited by a
4235 single = symbol. You can write out multiple records and read them
4236 back in with several calls to B<new>. You can do this across several
4237 sessions by opening the file in append mode, allowing you to create
4238 primitive guest books, or to keep a history of users' queries. Here's
4239 a short example of creating multiple session records:
4243 open (OUT,">>test.out") || die;
4245 foreach (0..$records) {
4247 $q->param(-name=>'counter',-value=>$_);
4252 # reopen for reading
4253 open (IN,"test.out") || die;
4255 my $q = new CGI(IN);
4256 print $q->param('counter'),"\n";
4259 The file format used for save/restore is identical to that used by the
4260 Whitehead Genome Center's data exchange format "Boulderio", and can be
4261 manipulated and even databased using Boulderio utilities. See
4263 http://stein.cshl.org/boulder/
4265 for further details.
4267 If you wish to use this method from the function-oriented (non-OO)
4268 interface, the exported name for this method is B<save_parameters()>.
4270 =head2 RETRIEVING CGI ERRORS
4272 Errors can occur while processing user input, particularly when
4273 processing uploaded files. When these errors occur, CGI will stop
4274 processing and return an empty parameter list. You can test for
4275 the existence and nature of errors using the I<cgi_error()> function.
4276 The error messages are formatted as HTTP status codes. You can either
4277 incorporate the error text into an HTML page, or use it as the value
4280 my $error = $q->cgi_error;
4282 print $q->header(-status=>$error),
4283 $q->start_html('Problems'),
4284 $q->h2('Request not processed'),
4289 When using the function-oriented interface (see the next section),
4290 errors may only occur the first time you call I<param()>. Be ready
4293 =head2 USING THE FUNCTION-ORIENTED INTERFACE
4295 To use the function-oriented interface, you must specify which CGI.pm
4296 routines or sets of routines to import into your script's namespace.
4297 There is a small overhead associated with this importation, but it
4300 use CGI <list of methods>;
4302 The listed methods will be imported into the current package; you can
4303 call them directly without creating a CGI object first. This example
4304 shows how to import the B<param()> and B<header()>
4305 methods, and then use them directly:
4307 use CGI 'param','header';
4308 print header('text/plain');
4309 $zipcode = param('zipcode');
4311 More frequently, you'll import common sets of functions by referring
4312 to the groups by name. All function sets are preceded with a ":"
4313 character as in ":html3" (for tags defined in the HTML 3 standard).
4315 Here is a list of the function sets you can import:
4321 Import all CGI-handling methods, such as B<param()>, B<path_info()>
4326 Import all fill-out form generating methods, such as B<textfield()>.
4330 Import all methods that generate HTML 2.0 standard elements.
4334 Import all methods that generate HTML 3.0 elements (such as
4335 <table>, <super> and <sub>).
4339 Import all methods that generate HTML 4 elements (such as
4340 <abbrev>, <acronym> and <thead>).
4344 Import all methods that generate Netscape-specific HTML extensions.
4348 Import all HTML-generating shortcuts (i.e. 'html2' + 'html3' +
4353 Import "standard" features, 'html2', 'html3', 'html4', 'form' and 'cgi'.
4357 Import all the available methods. For the full list, see the CGI.pm
4358 code, where the variable %EXPORT_TAGS is defined.
4362 If you import a function name that is not part of CGI.pm, the module
4363 will treat it as a new HTML tag and generate the appropriate
4364 subroutine. You can then use it like any other HTML tag. This is to
4365 provide for the rapidly-evolving HTML "standard." For example, say
4366 Microsoft comes out with a new tag called <gradient> (which causes the
4367 user's desktop to be flooded with a rotating gradient fill until his
4368 machine reboots). You don't need to wait for a new version of CGI.pm
4369 to start using it immediately:
4371 use CGI qw/:standard :html3 gradient/;
4372 print gradient({-start=>'red',-end=>'blue'});
4374 Note that in the interests of execution speed CGI.pm does B<not> use
4375 the standard L<Exporter> syntax for specifying load symbols. This may
4376 change in the future.
4378 If you import any of the state-maintaining CGI or form-generating
4379 methods, a default CGI object will be created and initialized
4380 automatically the first time you use any of the methods that require
4381 one to be present. This includes B<param()>, B<textfield()>,
4382 B<submit()> and the like. (If you need direct access to the CGI
4383 object, you can find it in the global variable B<$CGI::Q>). By
4384 importing CGI.pm methods, you can create visually elegant scripts:
4386 use CGI qw/:standard/;
4389 start_html('Simple Script'),
4390 h1('Simple Script'),
4392 "What's your name? ",textfield('name'),p,
4393 "What's the combination?",
4394 checkbox_group(-name=>'words',
4395 -values=>['eenie','meenie','minie','moe'],
4396 -defaults=>['eenie','moe']),p,
4397 "What's your favorite color?",
4398 popup_menu(-name=>'color',
4399 -values=>['red','green','blue','chartreuse']),p,
4406 "Your name is ",em(param('name')),p,
4407 "The keywords are: ",em(join(", ",param('words'))),p,
4408 "Your favorite color is ",em(param('color')),".\n";
4414 In addition to the function sets, there are a number of pragmas that
4415 you can import. Pragmas, which are always preceded by a hyphen,
4416 change the way that CGI.pm functions in various ways. Pragmas,
4417 function sets, and individual functions can all be imported in the
4418 same use() line. For example, the following use statement imports the
4419 standard set of functions and enables debugging mode (pragma
4422 use CGI qw/:standard -debug/;
4424 The current list of pragmas is as follows:
4430 When you I<use CGI -any>, then any method that the query object
4431 doesn't recognize will be interpreted as a new HTML tag. This allows
4432 you to support the next I<ad hoc> Netscape or Microsoft HTML
4433 extension. This lets you go wild with new and unsupported tags:
4437 print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
4439 Since using <cite>any</cite> causes any mistyped method name
4440 to be interpreted as an HTML tag, use it with care or not at
4445 This causes the indicated autoloaded methods to be compiled up front,
4446 rather than deferred to later. This is useful for scripts that run
4447 for an extended period of time under FastCGI or mod_perl, and for
4448 those destined to be crunched by Malcom Beattie's Perl compiler. Use
4449 it in conjunction with the methods or method families you plan to use.
4451 use CGI qw(-compile :standard :html3);
4455 use CGI qw(-compile :all);
4457 Note that using the -compile pragma in this way will always have
4458 the effect of importing the compiled functions into the current
4459 namespace. If you want to compile without importing use the
4460 compile() method instead:
4465 This is particularly useful in a mod_perl environment, in which you
4466 might want to precompile all CGI routines in a startup script, and
4467 then import the functions individually in each mod_perl script.
4471 This makes CGI.pm not generating the hidden fields .submit
4472 and .cgifields. It is very useful if you don't want to
4473 have the hidden fields appear in the querystring in a GET method.
4474 For example, a search script generated this way will have
4475 a very nice url with search parameters for bookmarking.
4477 =item -no_undef_params
4479 This keeps CGI.pm from including undef params in the parameter list.
4483 By default, CGI.pm versions 2.69 and higher emit XHTML
4484 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
4485 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for this
4490 This makes CGI.pm produce a header appropriate for an NPH (no
4491 parsed header) script. You may need to do other things as well
4492 to tell the server that the script is NPH. See the discussion
4493 of NPH scripts below.
4495 =item -newstyle_urls
4497 Separate the name=value pairs in CGI parameter query strings with
4498 semicolons rather than ampersands. For example:
4500 ?name=fred;age=24;favorite_color=3
4502 Semicolon-delimited query strings are always accepted, but will not be
4503 emitted by self_url() and query_string() unless the -newstyle_urls
4504 pragma is specified.
4506 This became the default in version 2.64.
4508 =item -oldstyle_urls
4510 Separate the name=value pairs in CGI parameter query strings with
4511 ampersands rather than semicolons. This is no longer the default.
4515 This overrides the autoloader so that any function in your program
4516 that is not recognized is referred to CGI.pm for possible evaluation.
4517 This allows you to use all the CGI.pm functions without adding them to
4518 your symbol table, which is of concern for mod_perl users who are
4519 worried about memory consumption. I<Warning:> when
4520 I<-autoload> is in effect, you cannot use "poetry mode"
4521 (functions without the parenthesis). Use I<hr()> rather
4522 than I<hr>, or add something like I<use subs qw/hr p header/>
4523 to the top of your script.
4527 This turns off the command-line processing features. If you want to
4528 run a CGI.pm script from the command line to produce HTML, and you
4529 don't want it to read CGI parameters from the command line or STDIN,
4530 then use this pragma:
4532 use CGI qw(-no_debug :standard);
4536 This turns on full debugging. In addition to reading CGI arguments
4537 from the command-line processing, CGI.pm will pause and try to read
4538 arguments from STDIN, producing the message "(offline mode: enter
4539 name=value pairs on standard input)" features.
4541 See the section on debugging for more details.
4543 =item -private_tempfiles
4545 CGI.pm can process uploaded file. Ordinarily it spools the uploaded
4546 file to a temporary directory, then deletes the file when done.
4547 However, this opens the risk of eavesdropping as described in the file
4548 upload section. Another CGI script author could peek at this data
4549 during the upload, even if it is confidential information. On Unix
4550 systems, the -private_tempfiles pragma will cause the temporary file
4551 to be unlinked as soon as it is opened and before any data is written
4552 into it, reducing, but not eliminating the risk of eavesdropping
4553 (there is still a potential race condition). To make life harder for
4554 the attacker, the program chooses tempfile names by calculating a 32
4555 bit checksum of the incoming HTTP headers.
4557 To ensure that the temporary file cannot be read by other CGI scripts,
4558 use suEXEC or a CGI wrapper program to run your script. The temporary
4559 file is created with mode 0600 (neither world nor group readable).
4561 The temporary directory is selected using the following algorithm:
4563 1. if the current user (e.g. "nobody") has a directory named
4564 "tmp" in its home directory, use that (Unix systems only).
4566 2. if the environment variable TMPDIR exists, use the location
4569 3. Otherwise try the locations /usr/tmp, /var/tmp, C:\temp,
4570 /tmp, /temp, ::Temporary Items, and \WWW_ROOT.
4572 Each of these locations is checked that it is a directory and is
4573 writable. If not, the algorithm tries the next choice.
4577 =head2 SPECIAL FORMS FOR IMPORTING HTML-TAG FUNCTIONS
4579 Many of the methods generate HTML tags. As described below, tag
4580 functions automatically generate both the opening and closing tags.
4583 print h1('Level 1 Header');
4587 <h1>Level 1 Header</h1>
4589 There will be some times when you want to produce the start and end
4590 tags yourself. In this case, you can use the form start_I<tag_name>
4591 and end_I<tag_name>, as in:
4593 print start_h1,'Level 1 Header',end_h1;
4595 With a few exceptions (described below), start_I<tag_name> and
4596 end_I<tag_name> functions are not generated automatically when you
4597 I<use CGI>. However, you can specify the tags you want to generate
4598 I<start/end> functions for by putting an asterisk in front of their
4599 name, or, alternatively, requesting either "start_I<tag_name>" or
4600 "end_I<tag_name>" in the import list.
4604 use CGI qw/:standard *table start_ul/;
4606 In this example, the following functions are generated in addition to
4611 =item 1. start_table() (generates a <table> tag)
4613 =item 2. end_table() (generates a </table> tag)
4615 =item 3. start_ul() (generates a <ul> tag)
4617 =item 4. end_ul() (generates a </ul> tag)
4621 =head1 GENERATING DYNAMIC DOCUMENTS
4623 Most of CGI.pm's functions deal with creating documents on the fly.
4624 Generally you will produce the HTTP header first, followed by the
4625 document itself. CGI.pm provides functions for generating HTTP
4626 headers of various types as well as for generating HTML. For creating
4627 GIF images, see the GD.pm module.
4629 Each of these functions produces a fragment of HTML or HTTP which you
4630 can print out directly so that it displays in the browser window,
4631 append to a string, or save to a file for later use.
4633 =head2 CREATING A STANDARD HTTP HEADER:
4635 Normally the first thing you will do in any CGI script is print out an
4636 HTTP header. This tells the browser what type of document to expect,
4637 and gives other optional information, such as the language, expiration
4638 date, and whether to cache the document. The header can also be
4639 manipulated for special purposes, such as server push and pay per view
4642 print $query->header;
4646 print $query->header('image/gif');
4650 print $query->header('text/html','204 No response');
4654 print $query->header(-type=>'image/gif',
4656 -status=>'402 Payment required',
4660 -attachment=>'foo.gif',
4663 header() returns the Content-type: header. You can provide your own
4664 MIME type if you choose, otherwise it defaults to text/html. An
4665 optional second parameter specifies the status code and a human-readable
4666 message. For example, you can specify 204, "No response" to create a
4667 script that tells the browser to do nothing at all.
4669 The last example shows the named argument style for passing arguments
4670 to the CGI methods using named parameters. Recognized parameters are
4671 B<-type>, B<-status>, B<-expires>, and B<-cookie>. Any other named
4672 parameters will be stripped of their initial hyphens and turned into
4673 header fields, allowing you to specify any HTTP header you desire.
4674 Internal underscores will be turned into hyphens:
4676 print $query->header(-Content_length=>3002);
4678 Most browsers will not cache the output from CGI scripts. Every time
4679 the browser reloads the page, the script is invoked anew. You can
4680 change this behavior with the B<-expires> parameter. When you specify
4681 an absolute or relative expiration interval with this parameter, some
4682 browsers and proxy servers will cache the script's output until the
4683 indicated expiration date. The following forms are all valid for the
4686 +30s 30 seconds from now
4687 +10m ten minutes from now
4688 +1h one hour from now
4689 -1d yesterday (i.e. "ASAP!")
4692 +10y in ten years time
4693 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
4695 The B<-cookie> parameter generates a header that tells the browser to provide
4696 a "magic cookie" during all subsequent transactions with your script.
4697 Netscape cookies have a special format that includes interesting attributes
4698 such as expiration time. Use the cookie() method to create and retrieve
4701 The B<-nph> parameter, if set to a true value, will issue the correct
4702 headers to work with a NPH (no-parse-header) script. This is important
4703 to use with certain servers that expect all their scripts to be NPH.
4705 The B<-charset> parameter can be used to control the character set
4706 sent to the browser. If not provided, defaults to ISO-8859-1. As a
4707 side effect, this sets the charset() method as well.
4709 The B<-attachment> parameter can be used to turn the page into an
4710 attachment. Instead of displaying the page, some browsers will prompt
4711 the user to save it to disk. The value of the argument is the
4712 suggested name for the saved file. In order for this to work, you may
4713 have to set the B<-type> to "application/octet-stream".
4715 The B<-p3p> parameter will add a P3P tag to the outgoing header. The
4716 parameter can be an arrayref or a space-delimited string of P3P tags.
4719 print header(-p3p=>[qw(CAO DSP LAW CURa)]);
4720 print header(-p3p=>'CAO DSP LAW CURa');
4722 In either case, the outgoing header will be formatted as:
4724 P3P: policyref="/w3c/p3p.xml" cp="CAO DSP LAW CURa"
4726 =head2 GENERATING A REDIRECTION HEADER
4728 print $query->redirect('http://somewhere.else/in/movie/land');
4730 Sometimes you don't want to produce a document yourself, but simply
4731 redirect the browser elsewhere, perhaps choosing a URL based on the
4732 time of day or the identity of the user.
4734 The redirect() function redirects the browser to a different URL. If
4735 you use redirection like this, you should B<not> print out a header as
4738 You should always use full URLs (including the http: or ftp: part) in
4739 redirection requests. Relative URLs will not work correctly.
4741 You can also use named arguments:
4743 print $query->redirect(-uri=>'http://somewhere.else/in/movie/land',
4746 The B<-nph> parameter, if set to a true value, will issue the correct
4747 headers to work with a NPH (no-parse-header) script. This is important
4748 to use with certain servers, such as Microsoft IIS, which
4749 expect all their scripts to be NPH.
4751 =head2 CREATING THE HTML DOCUMENT HEADER
4753 print $query->start_html(-title=>'Secrets of the Pyramids',
4754 -author=>'fred@capricorn.org',
4757 -meta=>{'keywords'=>'pharaoh secret mummy',
4758 'copyright'=>'copyright 1996 King Tut'},
4759 -style=>{'src'=>'/styles/style1.css'},
4762 After creating the HTTP header, most CGI scripts will start writing
4763 out an HTML document. The start_html() routine creates the top of the
4764 page, along with a lot of optional information that controls the
4765 page's appearance and behavior.
4767 This method returns a canned HTML header and the opening <body> tag.
4768 All parameters are optional. In the named parameter form, recognized
4769 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
4770 (see below for the explanation). Any additional parameters you
4771 provide, such as the Netscape unofficial BGCOLOR attribute, are added
4772 to the <body> tag. Additional parameters must be proceeded by a
4775 The argument B<-xbase> allows you to provide an HREF for the <base> tag
4776 different from the current location, as in
4778 -xbase=>"http://home.mcom.com/"
4780 All relative links will be interpreted relative to this tag.
4782 The argument B<-target> allows you to provide a default target frame
4783 for all the links and fill-out forms on the page. B<This is a
4784 non-standard HTTP feature which only works with Netscape browsers!>
4785 See the Netscape documentation on frames for details of how to
4788 -target=>"answer_window"
4790 All relative links will be interpreted relative to this tag.
4791 You add arbitrary meta information to the header with the B<-meta>
4792 argument. This argument expects a reference to an associative array
4793 containing name/value pairs of meta information. These will be turned
4794 into a series of header <meta> tags that look something like this:
4796 <meta name="keywords" content="pharaoh secret mummy">
4797 <meta name="description" content="copyright 1996 King Tut">
4799 To create an HTTP-EQUIV type of <meta> tag, use B<-head>, described
4802 The B<-style> argument is used to incorporate cascading stylesheets
4803 into your code. See the section on CASCADING STYLESHEETS for more
4806 The B<-lang> argument is used to incorporate a language attribute into
4807 the <html> tag. The default if not specified is "en-US" for US
4808 English. For example:
4810 print $q->start_html(-lang=>'fr-CA');
4812 To leave off the lang attribute, as you must do if you want to generate
4813 legal HTML 3.2 or earlier, pass the empty string (-lang=>'').
4815 The B<-encoding> argument can be used to specify the character set for
4816 XHTML. It defaults to iso-8859-1 if not specified.
4818 You can place other arbitrary HTML elements to the <head> section with the
4819 B<-head> tag. For example, to place the rarely-used <link> element in the
4820 head section, use this:
4822 print start_html(-head=>Link({-rel=>'next',
4823 -href=>'http://www.capricorn.com/s2.html'}));
4825 To incorporate multiple HTML elements into the <head> section, just pass an
4828 print start_html(-head=>[
4830 -href=>'http://www.capricorn.com/s2.html'}),
4831 Link({-rel=>'previous',
4832 -href=>'http://www.capricorn.com/s1.html'})
4836 And here's how to create an HTTP-EQUIV <meta> tag:
4838 print start_html(-head=>meta({-http_equiv => 'Content-Type',
4839 -content => 'text/html'}))
4842 JAVASCRIPTING: The B<-script>, B<-noScript>, B<-onLoad>,
4843 B<-onMouseOver>, B<-onMouseOut> and B<-onUnload> parameters are used
4844 to add Netscape JavaScript calls to your pages. B<-script> should
4845 point to a block of text containing JavaScript function definitions.
4846 This block will be placed within a <script> block inside the HTML (not
4847 HTTP) header. The block is placed in the header in order to give your
4848 page a fighting chance of having all its JavaScript functions in place
4849 even if the user presses the stop button before the page has loaded
4850 completely. CGI.pm attempts to format the script in such a way that
4851 JavaScript-naive browsers will not choke on the code: unfortunately
4852 there are some browsers, such as Chimera for Unix, that get confused
4855 The B<-onLoad> and B<-onUnload> parameters point to fragments of JavaScript
4856 code to execute when the page is respectively opened and closed by the
4857 browser. Usually these parameters are calls to functions defined in the
4861 print $query->header;
4863 // Ask a silly question
4864 function riddle_me_this() {
4865 var r = prompt("What walks on four legs in the morning, " +
4866 "two legs in the afternoon, " +
4867 "and three legs in the evening?");
4870 // Get a silly answer
4871 function response(answer) {
4872 if (answer == "man")
4873 alert("Right you are!");
4875 alert("Wrong! Guess again.");
4878 print $query->start_html(-title=>'The Riddle of the Sphinx',
4881 Use the B<-noScript> parameter to pass some HTML text that will be displayed on
4882 browsers that do not have JavaScript (or browsers where JavaScript is turned
4885 Netscape 3.0 recognizes several attributes of the <script> tag,
4886 including LANGUAGE and SRC. The latter is particularly interesting,
4887 as it allows you to keep the JavaScript code in a file or CGI script
4888 rather than cluttering up each page with the source. To use these
4889 attributes pass a HASH reference in the B<-script> parameter containing
4890 one or more of -language, -src, or -code:
4892 print $q->start_html(-title=>'The Riddle of the Sphinx',
4893 -script=>{-language=>'JAVASCRIPT',
4894 -src=>'/javascript/sphinx.js'}
4897 print $q->(-title=>'The Riddle of the Sphinx',
4898 -script=>{-language=>'PERLSCRIPT',
4899 -code=>'print "hello world!\n;"'}
4903 A final feature allows you to incorporate multiple <script> sections into the
4904 header. Just pass the list of script sections as an array reference.
4905 this allows you to specify different source files for different dialects
4906 of JavaScript. Example:
4908 print $q->start_html(-title=>'The Riddle of the Sphinx',
4910 { -language => 'JavaScript1.0',
4911 -src => '/javascript/utilities10.js'
4913 { -language => 'JavaScript1.1',
4914 -src => '/javascript/utilities11.js'
4916 { -language => 'JavaScript1.2',
4917 -src => '/javascript/utilities12.js'
4919 { -language => 'JavaScript28.2',
4920 -src => '/javascript/utilities219.js'
4925 If this looks a bit extreme, take my advice and stick with straight CGI scripting.
4929 http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/
4931 for more information about JavaScript.
4933 The old-style positional parameters are as follows:
4937 =item B<Parameters:>
4945 The author's e-mail address (will create a <link rev="MADE"> tag if present
4949 A 'true' flag if you want to include a <base> tag in the header. This
4950 helps resolve relative addresses to absolute ones when the document is moved,
4951 but makes the document hierarchy non-portable. Use with care!
4955 Any other parameters you want to include in the <body> tag. This is a good
4956 place to put Netscape extensions, such as colors and wallpaper patterns.
4960 =head2 ENDING THE HTML DOCUMENT:
4962 print $query->end_html
4964 This ends an HTML document by printing the </body></html> tags.
4966 =head2 CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION:
4968 $myself = $query->self_url;
4969 print q(<a href="$myself">I'm talking to myself.</a>);
4971 self_url() will return a URL, that, when selected, will reinvoke
4972 this script with all its state information intact. This is most
4973 useful when you want to jump around within the document using
4974 internal anchors but you don't want to disrupt the current contents
4975 of the form(s). Something like this will do the trick.
4977 $myself = $query->self_url;
4978 print "<a href=\"$myself#table1\">See table 1</a>";
4979 print "<a href=\"$myself#table2\">See table 2</a>";
4980 print "<a href=\"$myself#yourself\">See for yourself</a>";
4982 If you want more control over what's returned, using the B<url()>
4985 You can also retrieve the unprocessed query string with query_string():
4987 $the_string = $query->query_string;
4989 =head2 OBTAINING THE SCRIPT'S URL
4991 $full_url = $query->url();
4992 $full_url = $query->url(-full=>1); #alternative syntax
4993 $relative_url = $query->url(-relative=>1);
4994 $absolute_url = $query->url(-absolute=>1);
4995 $url_with_path = $query->url(-path_info=>1);
4996 $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
4997 $netloc = $query->url(-base => 1);
4999 B<url()> returns the script's URL in a variety of formats. Called
5000 without any arguments, it returns the full form of the URL, including
5001 host name and port number
5003 http://your.host.com/path/to/script.cgi
5005 You can modify this format with the following named arguments:
5011 If true, produce an absolute URL, e.g.
5017 Produce a relative URL. This is useful if you want to reinvoke your
5018 script with different parameters. For example:
5024 Produce the full URL, exactly as if called without any arguments.
5025 This overrides the -relative and -absolute arguments.
5027 =item B<-path> (B<-path_info>)
5029 Append the additional path information to the URL. This can be
5030 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
5031 is provided as a synonym.
5033 =item B<-query> (B<-query_string>)
5035 Append the query string to the URL. This can be combined with
5036 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
5041 Generate just the protocol and net location, as in http://www.foo.com:8000
5045 =head2 MIXING POST AND URL PARAMETERS
5047 $color = $query->url_param('color');
5049 It is possible for a script to receive CGI parameters in the URL as
5050 well as in the fill-out form by creating a form that POSTs to a URL
5051 containing a query string (a "?" mark followed by arguments). The
5052 B<param()> method will always return the contents of the POSTed
5053 fill-out form, ignoring the URL's query string. To retrieve URL
5054 parameters, call the B<url_param()> method. Use it in the same way as
5055 B<param()>. The main difference is that it allows you to read the
5056 parameters, but not set them.
5059 Under no circumstances will the contents of the URL query string
5060 interfere with similarly-named CGI parameters in POSTed forms. If you
5061 try to mix a URL query string with a form submitted with the GET
5062 method, the results will not be what you expect.
5064 =head1 CREATING STANDARD HTML ELEMENTS:
5066 CGI.pm defines general HTML shortcut methods for most, if not all of
5067 the HTML 3 and HTML 4 tags. HTML shortcuts are named after a single
5068 HTML element and return a fragment of HTML text that you can then
5069 print or manipulate as you like. Each shortcut returns a fragment of
5070 HTML code that you can append to a string, save to a file, or, most
5071 commonly, print out so that it displays in the browser window.
5073 This example shows how to use the HTML methods:
5076 print $q->blockquote(
5077 "Many years ago on the island of",
5078 $q->a({href=>"http://crete.org/"},"Crete"),
5079 "there lived a Minotaur named",
5080 $q->strong("Fred."),
5084 This results in the following HTML code (extra newlines have been
5085 added for readability):
5088 Many years ago on the island of
5089 <a href="http://crete.org/">Crete</a> there lived
5090 a minotaur named <strong>Fred.</strong>
5094 If you find the syntax for calling the HTML shortcuts awkward, you can
5095 import them into your namespace and dispense with the object syntax
5096 completely (see the next section for more details):
5098 use CGI ':standard';
5100 "Many years ago on the island of",
5101 a({href=>"http://crete.org/"},"Crete"),
5102 "there lived a minotaur named",
5107 =head2 PROVIDING ARGUMENTS TO HTML SHORTCUTS
5109 The HTML methods will accept zero, one or multiple arguments. If you
5110 provide no arguments, you get a single tag:
5114 If you provide one or more string arguments, they are concatenated
5115 together with spaces and placed between opening and closing tags:
5117 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
5119 If the first argument is an associative array reference, then the keys
5120 and values of the associative array become the HTML tag's attributes:
5122 print a({-href=>'fred.html',-target=>'_new'},
5123 "Open a new frame");
5125 <a href="fred.html",target="_new">Open a new frame</a>
5127 You may dispense with the dashes in front of the attribute names if
5130 print img {src=>'fred.gif',align=>'LEFT'};
5132 <img align="LEFT" src="fred.gif">
5134 Sometimes an HTML tag attribute has no argument. For example, ordered
5135 lists can be marked as COMPACT. The syntax for this is an argument that
5136 that points to an undef string:
5138 print ol({compact=>undef},li('one'),li('two'),li('three'));
5140 Prior to CGI.pm version 2.41, providing an empty ('') string as an
5141 attribute argument was the same as providing undef. However, this has
5142 changed in order to accommodate those who want to create tags of the form
5143 <img alt="">. The difference is shown in these two pieces of code:
5146 img({alt=>undef}) <img alt>
5147 img({alt=>''}) <img alt="">
5149 =head2 THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS
5151 One of the cool features of the HTML shortcuts is that they are
5152 distributive. If you give them an argument consisting of a
5153 B<reference> to a list, the tag will be distributed across each
5154 element of the list. For example, here's one way to make an ordered
5158 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
5161 This example will result in HTML output that looks like this:
5164 <li type="disc">Sneezy</li>
5165 <li type="disc">Doc</li>
5166 <li type="disc">Sleepy</li>
5167 <li type="disc">Happy</li>
5170 This is extremely useful for creating tables. For example:
5172 print table({-border=>undef},
5173 caption('When Should You Eat Your Vegetables?'),
5174 Tr({-align=>CENTER,-valign=>TOP},
5176 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
5177 td(['Tomatoes' , 'no', 'yes', 'yes']),
5178 td(['Broccoli' , 'no', 'no', 'yes']),
5179 td(['Onions' , 'yes','yes', 'yes'])
5184 =head2 HTML SHORTCUTS AND LIST INTERPOLATION
5186 Consider this bit of code:
5188 print blockquote(em('Hi'),'mom!'));
5190 It will ordinarily return the string that you probably expect, namely:
5192 <blockquote><em>Hi</em> mom!</blockquote>
5194 Note the space between the element "Hi" and the element "mom!".
5195 CGI.pm puts the extra space there using array interpolation, which is
5196 controlled by the magic $" variable. Sometimes this extra space is
5197 not what you want, for example, when you are trying to align a series
5198 of images. In this case, you can simply change the value of $" to an
5203 print blockquote(em('Hi'),'mom!'));
5206 I suggest you put the code in a block as shown here. Otherwise the
5207 change to $" will affect all subsequent code until you explicitly
5210 =head2 NON-STANDARD HTML SHORTCUTS
5212 A few HTML tags don't follow the standard pattern for various
5215 B<comment()> generates an HTML comment (<!-- comment -->). Call it
5218 print comment('here is my comment');
5220 Because of conflicts with built-in Perl functions, the following functions
5221 begin with initial caps:
5230 In addition, start_html(), end_html(), start_form(), end_form(),
5231 start_multipart_form() and all the fill-out form tags are special.
5232 See their respective sections.
5234 =head2 AUTOESCAPING HTML
5236 By default, all HTML that is emitted by the form-generating functions
5237 is passed through a function called escapeHTML():
5241 =item $escaped_string = escapeHTML("unescaped string");
5243 Escape HTML formatting characters in a string.
5247 Provided that you have specified a character set of ISO-8859-1 (the
5248 default), the standard HTML escaping rules will be used. The "<"
5249 character becomes "<", ">" becomes ">", "&" becomes "&", and
5250 the quote character becomes """. In addition, the hexadecimal
5251 0x8b and 0x9b characters, which some browsers incorrectly interpret
5252 as the left and right angle-bracket characters, are replaced by their
5253 numeric character entities ("‹" and "›"). If you manually change
5254 the charset, either by calling the charset() method explicitly or by
5255 passing a -charset argument to header(), then B<all> characters will
5256 be replaced by their numeric entities, since CGI.pm has no lookup
5257 table for all the possible encodings.
5259 The automatic escaping does not apply to other shortcuts, such as
5260 h1(). You should call escapeHTML() yourself on untrusted data in
5261 order to protect your pages against nasty tricks that people may enter
5262 into guestbooks, etc.. To change the character set, use charset().
5263 To turn autoescaping off completely, use autoEscape(0):
5267 =item $charset = charset([$charset]);
5269 Get or set the current character set.
5271 =item $flag = autoEscape([$flag]);
5273 Get or set the value of the autoescape flag.
5277 =head2 PRETTY-PRINTING HTML
5279 By default, all the HTML produced by these functions comes out as one
5280 long line without carriage returns or indentation. This is yuck, but
5281 it does reduce the size of the documents by 10-20%. To get
5282 pretty-printed output, please use L<CGI::Pretty>, a subclass
5283 contributed by Brian Paulsen.
5285 =head1 CREATING FILL-OUT FORMS:
5287 I<General note> The various form-creating methods all return strings
5288 to the caller, containing the tag or tags that will create the requested
5289 form element. You are responsible for actually printing out these strings.
5290 It's set up this way so that you can place formatting tags
5291 around the form elements.
5293 I<Another note> The default values that you specify for the forms are only
5294 used the B<first> time the script is invoked (when there is no query
5295 string). On subsequent invocations of the script (when there is a query
5296 string), the former values are used even if they are blank.
5298 If you want to change the value of a field from its previous value, you have two
5301 (1) call the param() method to set it.
5303 (2) use the -override (alias -force) parameter (a new feature in version 2.15).
5304 This forces the default value to be used, regardless of the previous value:
5306 print $query->textfield(-name=>'field_name',
5307 -default=>'starting value',
5312 I<Yet another note> By default, the text and labels of form elements are
5313 escaped according to HTML rules. This means that you can safely use
5314 "<CLICK ME>" as the label for a button. However, it also interferes with
5315 your ability to incorporate special HTML character sequences, such as Á,
5316 into your fields. If you wish to turn off automatic escaping, call the
5317 autoEscape() method with a false value immediately after creating the CGI object:
5320 $query->autoEscape(undef);
5322 =head2 CREATING AN ISINDEX TAG
5324 print $query->isindex(-action=>$action);
5328 print $query->isindex($action);
5330 Prints out an <isindex> tag. Not very exciting. The parameter
5331 -action specifies the URL of the script to process the query. The
5332 default is to process the query with the current script.
5334 =head2 STARTING AND ENDING A FORM
5336 print $query->start_form(-method=>$method,
5338 -enctype=>$encoding);
5339 <... various form stuff ...>
5340 print $query->endform;
5344 print $query->start_form($method,$action,$encoding);
5345 <... various form stuff ...>
5346 print $query->endform;
5348 start_form() will return a <form> tag with the optional method,
5349 action and form encoding that you specify. The defaults are:
5353 enctype: application/x-www-form-urlencoded
5355 endform() returns the closing </form> tag.
5357 Start_form()'s enctype argument tells the browser how to package the various
5358 fields of the form before sending the form to the server. Two
5359 values are possible:
5361 B<Note:> This method was previously named startform(), and startform()
5362 is still recognized as an alias.
5366 =item B<application/x-www-form-urlencoded>
5368 This is the older type of encoding used by all browsers prior to
5369 Netscape 2.0. It is compatible with many CGI scripts and is
5370 suitable for short fields containing text data. For your
5371 convenience, CGI.pm stores the name of this encoding
5372 type in B<&CGI::URL_ENCODED>.
5374 =item B<multipart/form-data>
5376 This is the newer type of encoding introduced by Netscape 2.0.
5377 It is suitable for forms that contain very large fields or that
5378 are intended for transferring binary data. Most importantly,
5379 it enables the "file upload" feature of Netscape 2.0 forms. For
5380 your convenience, CGI.pm stores the name of this encoding type
5381 in B<&CGI::MULTIPART>
5383 Forms that use this type of encoding are not easily interpreted
5384 by CGI scripts unless they use CGI.pm or another library designed
5389 For compatibility, the start_form() method uses the older form of
5390 encoding by default. If you want to use the newer form of encoding
5391 by default, you can call B<start_multipart_form()> instead of
5394 JAVASCRIPTING: The B<-name> and B<-onSubmit> parameters are provided
5395 for use with JavaScript. The -name parameter gives the
5396 form a name so that it can be identified and manipulated by
5397 JavaScript functions. -onSubmit should point to a JavaScript
5398 function that will be executed just before the form is submitted to your
5399 server. You can use this opportunity to check the contents of the form
5400 for consistency and completeness. If you find something wrong, you
5401 can put up an alert box or maybe fix things up yourself. You can
5402 abort the submission by returning false from this function.
5404 Usually the bulk of JavaScript functions are defined in a <script>
5405 block in the HTML header and -onSubmit points to one of these function
5406 call. See start_html() for details.
5408 =head2 CREATING A TEXT FIELD
5410 print $query->textfield(-name=>'field_name',
5411 -default=>'starting value',
5416 print $query->textfield('field_name','starting value',50,80);
5418 textfield() will return a text input field.
5426 The first parameter is the required name for the field (-name).
5430 The optional second parameter is the default starting value for the field
5431 contents (-default).
5435 The optional third parameter is the size of the field in
5440 The optional fourth parameter is the maximum number of characters the
5441 field will accept (-maxlength).
5445 As with all these methods, the field will be initialized with its
5446 previous contents from earlier invocations of the script.
5447 When the form is processed, the value of the text field can be
5450 $value = $query->param('foo');
5452 If you want to reset it from its initial value after the script has been
5453 called once, you can do so like this:
5455 $query->param('foo',"I'm taking over this value!");
5457 NEW AS OF VERSION 2.15: If you don't want the field to take on its previous
5458 value, you can force its current value by using the -override (alias -force)
5461 print $query->textfield(-name=>'field_name',
5462 -default=>'starting value',
5467 JAVASCRIPTING: You can also provide B<-onChange>, B<-onFocus>,
5468 B<-onBlur>, B<-onMouseOver>, B<-onMouseOut> and B<-onSelect>
5469 parameters to register JavaScript event handlers. The onChange
5470 handler will be called whenever the user changes the contents of the
5471 text field. You can do text validation if you like. onFocus and
5472 onBlur are called respectively when the insertion point moves into and
5473 out of the text field. onSelect is called when the user changes the
5474 portion of the text that is selected.
5476 =head2 CREATING A BIG TEXT FIELD
5478 print $query->textarea(-name=>'foo',
5479 -default=>'starting value',
5485 print $query->textarea('foo','starting value',10,50);
5487 textarea() is just like textfield, but it allows you to specify
5488 rows and columns for a multiline text entry box. You can provide
5489 a starting value for the field, which can be long and contain
5492 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur> ,
5493 B<-onMouseOver>, B<-onMouseOut>, and B<-onSelect> parameters are
5494 recognized. See textfield().
5496 =head2 CREATING A PASSWORD FIELD
5498 print $query->password_field(-name=>'secret',
5499 -value=>'starting value',
5504 print $query->password_field('secret','starting value',50,80);
5506 password_field() is identical to textfield(), except that its contents
5507 will be starred out on the web page.
5509 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5510 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5511 recognized. See textfield().
5513 =head2 CREATING A FILE UPLOAD FIELD
5515 print $query->filefield(-name=>'uploaded_file',
5516 -default=>'starting value',
5521 print $query->filefield('uploaded_file','starting value',50,80);
5523 filefield() will return a file upload field for Netscape 2.0 browsers.
5524 In order to take full advantage of this I<you must use the new
5525 multipart encoding scheme> for the form. You can do this either
5526 by calling B<start_form()> with an encoding type of B<&CGI::MULTIPART>,
5527 or by calling the new method B<start_multipart_form()> instead of
5528 vanilla B<start_form()>.
5536 The first parameter is the required name for the field (-name).
5540 The optional second parameter is the starting value for the field contents
5541 to be used as the default file name (-default).
5543 For security reasons, browsers don't pay any attention to this field,
5544 and so the starting value will always be blank. Worse, the field
5545 loses its "sticky" behavior and forgets its previous contents. The
5546 starting value field is called for in the HTML specification, however,
5547 and possibly some browser will eventually provide support for it.
5551 The optional third parameter is the size of the field in
5556 The optional fourth parameter is the maximum number of characters the
5557 field will accept (-maxlength).
5561 When the form is processed, you can retrieve the entered filename
5564 $filename = $query->param('uploaded_file');
5566 Different browsers will return slightly different things for the
5567 name. Some browsers return the filename only. Others return the full
5568 path to the file, using the path conventions of the user's machine.
5569 Regardless, the name returned is always the name of the file on the
5570 I<user's> machine, and is unrelated to the name of the temporary file
5571 that CGI.pm creates during upload spooling (see below).
5573 The filename returned is also a file handle. You can read the contents
5574 of the file using standard Perl file reading calls:
5576 # Read a text file and print it out
5577 while (<$filename>) {
5581 # Copy a binary file to somewhere safe
5582 open (OUTFILE,">>/usr/local/web/users/feedback");
5583 while ($bytesread=read($filename,$buffer,1024)) {
5584 print OUTFILE $buffer;
5587 However, there are problems with the dual nature of the upload fields.
5588 If you C<use strict>, then Perl will complain when you try to use a
5589 string as a filehandle. You can get around this by placing the file
5590 reading code in a block containing the C<no strict> pragma. More
5591 seriously, it is possible for the remote user to type garbage into the
5592 upload field, in which case what you get from param() is not a
5593 filehandle at all, but a string.
5595 To be safe, use the I<upload()> function (new in version 2.47). When
5596 called with the name of an upload field, I<upload()> returns a
5597 filehandle, or undef if the parameter is not a valid filehandle.
5599 $fh = $query->upload('uploaded_file');
5604 In an array context, upload() will return an array of filehandles.
5605 This makes it possible to create forms that use the same name for
5606 multiple upload fields.
5608 This is the recommended idiom.
5610 When a file is uploaded the browser usually sends along some
5611 information along with it in the format of headers. The information
5612 usually includes the MIME content type. Future browsers may send
5613 other information as well (such as modification date and size). To
5614 retrieve this information, call uploadInfo(). It returns a reference to
5615 an associative array containing all the document headers.
5617 $filename = $query->param('uploaded_file');
5618 $type = $query->uploadInfo($filename)->{'Content-Type'};
5619 unless ($type eq 'text/html') {
5620 die "HTML FILES ONLY!";
5623 If you are using a machine that recognizes "text" and "binary" data
5624 modes, be sure to understand when and how to use them (see the Camel book).
5625 Otherwise you may find that binary files are corrupted during file
5628 There are occasionally problems involving parsing the uploaded file.
5629 This usually happens when the user presses "Stop" before the upload is
5630 finished. In this case, CGI.pm will return undef for the name of the
5631 uploaded file and set I<cgi_error()> to the string "400 Bad request
5632 (malformed multipart POST)". This error message is designed so that
5633 you can incorporate it into a status code to be sent to the browser.
5636 $file = $query->upload('uploaded_file');
5637 if (!$file && $query->cgi_error) {
5638 print $query->header(-status=>$query->cgi_error);
5642 You are free to create a custom HTML page to complain about the error,
5645 You can set up a callback that will be called whenever a file upload
5646 is being read during the form processing. This is much like the
5647 UPLOAD_HOOK facility available in Apache::Request, with the exception
5648 that the first argument to the callback is an Apache::Upload object,
5649 here it's the remote filename.
5652 $q->upload_hook(\&hook,$data);
5656 my ($filename, $buffer, $bytes_read, $data) = @_;
5657 print "Read $bytes_read bytes of $filename\n";
5660 If using the function-oriented interface, call the CGI::upload_hook()
5661 method before calling param() or any other CGI functions:
5663 CGI::upload_hook(\&hook,$data);
5665 This method is not exported by default. You will have to import it
5666 explicitly if you wish to use it without the CGI:: prefix.
5668 If you are using CGI.pm on a Windows platform and find that binary
5669 files get slightly larger when uploaded but that text files remain the
5670 same, then you have forgotten to activate binary mode on the output
5671 filehandle. Be sure to call binmode() on any handle that you create
5672 to write the uploaded file to disk.
5674 JAVASCRIPTING: The B<-onChange>, B<-onFocus>, B<-onBlur>,
5675 B<-onMouseOver>, B<-onMouseOut> and B<-onSelect> parameters are
5676 recognized. See textfield() for details.
5678 =head2 CREATING A POPUP MENU
5680 print $query->popup_menu('menu_name',
5681 ['eenie','meenie','minie'],
5686 %labels = ('eenie'=>'your first choice',
5687 'meenie'=>'your second choice',
5688 'minie'=>'your third choice');
5689 %attributes = ('eenie'=>{'class'=>'class of first choice'});
5690 print $query->popup_menu('menu_name',
5691 ['eenie','meenie','minie'],
5692 'meenie',\%labels,\%attributes);
5694 -or (named parameter style)-
5696 print $query->popup_menu(-name=>'menu_name',
5697 -values=>['eenie','meenie','minie'],
5700 -attributes=>\%attributes);
5702 popup_menu() creates a menu.
5708 The required first argument is the menu's name (-name).
5712 The required second argument (-values) is an array B<reference>
5713 containing the list of menu items in the menu. You can pass the
5714 method an anonymous array, as shown in the example, or a reference to
5715 a named array, such as "\@foo".
5719 The optional third parameter (-default) is the name of the default
5720 menu choice. If not specified, the first item will be the default.
5721 The values of the previous choice will be maintained across queries.
5725 The optional fourth parameter (-labels) is provided for people who
5726 want to use different values for the user-visible label inside the
5727 popup menu and the value returned to your script. It's a pointer to an
5728 associative array relating menu values to user-visible labels. If you
5729 leave this parameter blank, the menu values will be displayed by
5730 default. (You can also leave a label undefined if you want to).
5734 The optional fifth parameter (-attributes) is provided to assign
5735 any of the common HTML attributes to an individual menu item. It's
5736 a pointer to an associative array relating menu values to another
5737 associative array with the attribute's name as the key and the
5738 attribute's value as the value.
5742 When the form is processed, the selected value of the popup menu can
5745 $popup_menu_value = $query->param('menu_name');
5747 JAVASCRIPTING: popup_menu() recognizes the following event handlers:
5748 B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>, and
5749 B<-onBlur>. See the textfield() section for details on when these
5750 handlers are called.
5752 =head2 CREATING AN OPTION GROUP
5754 Named parameter style
5756 print $query->popup_menu(-name=>'menu_name',
5757 -values=>[qw/eenie meenie minie/,
5758 $q->optgroup(-name=>'optgroup_name',
5759 -values ['moe','catch'],
5760 -attributes=>{'catch'=>{'class'=>'red'}}),
5761 -labels=>{'eenie'=>'one',
5764 -default=>'meenie');
5767 print $query->popup_menu('menu_name',
5768 ['eenie','meenie','minie',
5769 $q->optgroup('optgroup_name', ['moe', 'catch'],
5770 {'catch'=>{'class'=>'red'}})],'meenie',
5771 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
5773 optgroup creates an option group within a popup menu.
5779 The required first argument (B<-name>) is the label attribute of the
5780 optgroup and is B<not> inserted in the parameter list of the query.
5784 The required second argument (B<-values>) is an array reference
5785 containing the list of menu items in the menu. You can pass the
5786 method an anonymous array, as shown in the example, or a reference
5787 to a named array, such as \@foo. If you pass a HASH reference,
5788 the keys will be used for the menu values, and the values will be
5789 used for the menu labels (see -labels below).
5793 The optional third parameter (B<-labels>) allows you to pass a reference
5794 to an associative array containing user-visible labels for one or more
5795 of the menu items. You can use this when you want the user to see one
5796 menu string, but have the browser return your program a different one.
5797 If you don't specify this, the value string will be used instead
5798 ("eenie", "meenie" and "minie" in this example). This is equivalent
5799 to using a hash reference for the -values parameter.
5803 An optional fourth parameter (B<-labeled>) can be set to a true value
5804 and indicates that the values should be used as the label attribute
5805 for each option element within the optgroup.
5809 An optional fifth parameter (-novals) can be set to a true value and
5810 indicates to suppress the val attribut in each option element within
5813 See the discussion on optgroup at W3C
5814 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
5819 An optional sixth parameter (-attributes) is provided to assign
5820 any of the common HTML attributes to an individual menu item. It's
5821 a pointer to an associative array relating menu values to another
5822 associative array with the attribute's name as the key and the
5823 attribute's value as the value.
5827 =head2 CREATING A SCROLLING LIST
5829 print $query->scrolling_list('list_name',
5830 ['eenie','meenie','minie','moe'],
5831 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
5834 print $query->scrolling_list('list_name',
5835 ['eenie','meenie','minie','moe'],
5836 ['eenie','moe'],5,'true',
5837 \%labels,%attributes);
5841 print $query->scrolling_list(-name=>'list_name',
5842 -values=>['eenie','meenie','minie','moe'],
5843 -default=>['eenie','moe'],
5847 -attributes=>\%attributes);
5849 scrolling_list() creates a scrolling list.
5853 =item B<Parameters:>
5857 The first and second arguments are the list name (-name) and values
5858 (-values). As in the popup menu, the second argument should be an
5863 The optional third argument (-default) can be either a reference to a
5864 list containing the values to be selected by default, or can be a
5865 single value to select. If this argument is missing or undefined,
5866 then nothing is selected when the list first appears. In the named
5867 parameter version, you can use the synonym "-defaults" for this
5872 The optional fourth argument is the size of the list (-size).
5876 The optional fifth argument can be set to true to allow multiple
5877 simultaneous selections (-multiple). Otherwise only one selection
5878 will be allowed at a time.
5882 The optional sixth argument is a pointer to an associative array
5883 containing long user-visible labels for the list items (-labels).
5884 If not provided, the values will be displayed.
5888 The optional sixth parameter (-attributes) is provided to assign
5889 any of the common HTML attributes to an individual menu item. It's
5890 a pointer to an associative array relating menu values to another
5891 associative array with the attribute's name as the key and the
5892 attribute's value as the value.
5894 When this form is processed, all selected list items will be returned as
5895 a list under the parameter name 'list_name'. The values of the
5896 selected items can be retrieved with:
5898 @selected = $query->param('list_name');
5902 JAVASCRIPTING: scrolling_list() recognizes the following event
5903 handlers: B<-onChange>, B<-onFocus>, B<-onMouseOver>, B<-onMouseOut>
5904 and B<-onBlur>. See textfield() for the description of when these
5905 handlers are called.
5907 =head2 CREATING A GROUP OF RELATED CHECKBOXES
5909 print $query->checkbox_group(-name=>'group_name',
5910 -values=>['eenie','meenie','minie','moe'],
5911 -default=>['eenie','moe'],
5914 -attributes=>\%attributes);
5916 print $query->checkbox_group('group_name',
5917 ['eenie','meenie','minie','moe'],
5918 ['eenie','moe'],'true',\%labels,
5919 {'moe'=>{'class'=>'red'}});
5921 HTML3-COMPATIBLE BROWSERS ONLY:
5923 print $query->checkbox_group(-name=>'group_name',
5924 -values=>['eenie','meenie','minie','moe'],
5925 -rows=2,-columns=>2);
5928 checkbox_group() creates a list of checkboxes that are related
5933 =item B<Parameters:>
5937 The first and second arguments are the checkbox name and values,
5938 respectively (-name and -values). As in the popup menu, the second
5939 argument should be an array reference. These values are used for the
5940 user-readable labels printed next to the checkboxes as well as for the
5941 values passed to your script in the query string.
5945 The optional third argument (-default) can be either a reference to a
5946 list containing the values to be checked by default, or can be a
5947 single value to checked. If this argument is missing or undefined,
5948 then nothing is selected when the list first appears.
5952 The optional fourth argument (-linebreak) can be set to true to place
5953 line breaks between the checkboxes so that they appear as a vertical
5954 list. Otherwise, they will be strung together on a horizontal line.
5958 The optional fifth argument is a pointer to an associative array
5959 relating the checkbox values to the user-visible labels that will
5960 be printed next to them (-labels). If not provided, the values will
5961 be used as the default.
5965 B<HTML3-compatible browsers> (such as Netscape) can take advantage of
5966 the optional parameters B<-rows>, and B<-columns>. These parameters
5967 cause checkbox_group() to return an HTML3 compatible table containing
5968 the checkbox group formatted with the specified number of rows and
5969 columns. You can provide just the -columns parameter if you wish;
5970 checkbox_group will calculate the correct number of rows for you.
5974 The optional sixth parameter (-attributes) is provided to assign
5975 any of the common HTML attributes to an individual menu item. It's
5976 a pointer to an associative array relating menu values to another
5977 associative array with the attribute's name as the key and the
5978 attribute's value as the value.
5980 To include row and column headings in the returned table, you
5981 can use the B<-rowheaders> and B<-colheaders> parameters. Both
5982 of these accept a pointer to an array of headings to use.
5983 The headings are just decorative. They don't reorganize the
5984 interpretation of the checkboxes -- they're still a single named
5989 When the form is processed, all checked boxes will be returned as
5990 a list under the parameter name 'group_name'. The values of the
5991 "on" checkboxes can be retrieved with:
5993 @turned_on = $query->param('group_name');
5995 The value returned by checkbox_group() is actually an array of button
5996 elements. You can capture them and use them within tables, lists,
5997 or in other creative ways:
5999 @h = $query->checkbox_group(-name=>'group_name',-values=>\@values);
6000 &use_in_creative_way(@h);
6002 JAVASCRIPTING: checkbox_group() recognizes the B<-onClick>
6003 parameter. This specifies a JavaScript code fragment or
6004 function call to be executed every time the user clicks on
6005 any of the buttons in the group. You can retrieve the identity
6006 of the particular button clicked on using the "this" variable.
6008 =head2 CREATING A STANDALONE CHECKBOX
6010 print $query->checkbox(-name=>'checkbox_name',
6013 -label=>'CLICK ME');
6017 print $query->checkbox('checkbox_name','checked','ON','CLICK ME');
6019 checkbox() is used to create an isolated checkbox that isn't logically
6020 related to any others.
6024 =item B<Parameters:>
6028 The first parameter is the required name for the checkbox (-name). It
6029 will also be used for the user-readable label printed next to the
6034 The optional second parameter (-checked) specifies that the checkbox
6035 is turned on by default. Synonyms are -selected and -on.
6039 The optional third parameter (-value) specifies the value of the
6040 checkbox when it is checked. If not provided, the word "on" is
6045 The optional fourth parameter (-label) is the user-readable label to
6046 be attached to the checkbox. If not provided, the checkbox name is
6051 The value of the checkbox can be retrieved using:
6053 $turned_on = $query->param('checkbox_name');
6055 JAVASCRIPTING: checkbox() recognizes the B<-onClick>
6056 parameter. See checkbox_group() for further details.
6058 =head2 CREATING A RADIO BUTTON GROUP
6060 print $query->radio_group(-name=>'group_name',
6061 -values=>['eenie','meenie','minie'],
6065 -attributes=>\%attributes);
6069 print $query->radio_group('group_name',['eenie','meenie','minie'],
6070 'meenie','true',\%labels,\%attributes);
6073 HTML3-COMPATIBLE BROWSERS ONLY:
6075 print $query->radio_group(-name=>'group_name',
6076 -values=>['eenie','meenie','minie','moe'],
6077 -rows=2,-columns=>2);
6079 radio_group() creates a set of logically-related radio buttons
6080 (turning one member of the group on turns the others off)
6084 =item B<Parameters:>
6088 The first argument is the name of the group and is required (-name).
6092 The second argument (-values) is the list of values for the radio
6093 buttons. The values and the labels that appear on the page are
6094 identical. Pass an array I<reference> in the second argument, either
6095 using an anonymous array, as shown, or by referencing a named array as
6100 The optional third parameter (-default) is the name of the default
6101 button to turn on. If not specified, the first item will be the
6102 default. You can provide a nonexistent button name, such as "-" to
6103 start up with no buttons selected.
6107 The optional fourth parameter (-linebreak) can be set to 'true' to put
6108 line breaks between the buttons, creating a vertical list.
6112 The optional fifth parameter (-labels) is a pointer to an associative
6113 array relating the radio button values to user-visible labels to be
6114 used in the display. If not provided, the values themselves are
6119 B<HTML3-compatible browsers> (such as Netscape) can take advantage
6121 parameters B<-rows>, and B<-columns>. These parameters cause
6122 radio_group() to return an HTML3 compatible table containing
6123 the radio group formatted with the specified number of rows
6124 and columns. You can provide just the -columns parameter if you
6125 wish; radio_group will calculate the correct number of rows
6130 The optional sixth parameter (-attributes) is provided to assign
6131 any of the common HTML attributes to an individual menu item. It's
6132 a pointer to an associative array relating menu values to another
6133 associative array with the attribute's name as the key and the
6134 attribute's value as the value.
6136 To include row and column headings in the returned table, you
6137 can use the B<-rowheader> and B<-colheader> parameters. Both
6138 of these accept a pointer to an array of headings to use.
6139 The headings are just decorative. They don't reorganize the
6140 interpretation of the radio buttons -- they're still a single named
6145 When the form is processed, the selected radio button can
6148 $which_radio_button = $query->param('group_name');
6150 The value returned by radio_group() is actually an array of button
6151 elements. You can capture them and use them within tables, lists,
6152 or in other creative ways:
6154 @h = $query->radio_group(-name=>'group_name',-values=>\@values);
6155 &use_in_creative_way(@h);
6157 =head2 CREATING A SUBMIT BUTTON
6159 print $query->submit(-name=>'button_name',
6164 print $query->submit('button_name','value');
6166 submit() will create the query submission button. Every form
6167 should have one of these.
6171 =item B<Parameters:>
6175 The first argument (-name) is optional. You can give the button a
6176 name if you have several submission buttons in your form and you want
6177 to distinguish between them. The name will also be used as the
6178 user-visible label. Be aware that a few older browsers don't deal with this correctly and
6179 B<never> send back a value from a button.
6183 The second argument (-value) is also optional. This gives the button
6184 a value that will be passed to your script in the query string.
6188 You can figure out which button was pressed by using different
6189 values for each one:
6191 $which_one = $query->param('button_name');
6193 JAVASCRIPTING: radio_group() recognizes the B<-onClick>
6194 parameter. See checkbox_group() for further details.
6196 =head2 CREATING A RESET BUTTON
6200 reset() creates the "reset" button. Note that it restores the
6201 form to its value from the last time the script was called,
6202 NOT necessarily to the defaults.
6204 Note that this conflicts with the Perl reset() built-in. Use
6205 CORE::reset() to get the original reset function.
6207 =head2 CREATING A DEFAULT BUTTON
6209 print $query->defaults('button_label')
6211 defaults() creates a button that, when invoked, will cause the
6212 form to be completely reset to its defaults, wiping out all the
6213 changes the user ever made.
6215 =head2 CREATING A HIDDEN FIELD
6217 print $query->hidden(-name=>'hidden_name',
6218 -default=>['value1','value2'...]);
6222 print $query->hidden('hidden_name','value1','value2'...);
6224 hidden() produces a text field that can't be seen by the user. It
6225 is useful for passing state variable information from one invocation
6226 of the script to the next.
6230 =item B<Parameters:>
6234 The first argument is required and specifies the name of this
6239 The second argument is also required and specifies its value
6240 (-default). In the named parameter style of calling, you can provide
6241 a single value here or a reference to a whole list
6245 Fetch the value of a hidden field this way:
6247 $hidden_value = $query->param('hidden_name');
6249 Note, that just like all the other form elements, the value of a
6250 hidden field is "sticky". If you want to replace a hidden field with
6251 some other values after the script has been called once you'll have to
6254 $query->param('hidden_name','new','values','here');
6256 =head2 CREATING A CLICKABLE IMAGE BUTTON
6258 print $query->image_button(-name=>'button_name',
6259 -src=>'/source/URL',
6264 print $query->image_button('button_name','/source/URL','MIDDLE');
6266 image_button() produces a clickable image. When it's clicked on the
6267 position of the click is returned to your script as "button_name.x"
6268 and "button_name.y", where "button_name" is the name you've assigned
6271 JAVASCRIPTING: image_button() recognizes the B<-onClick>
6272 parameter. See checkbox_group() for further details.
6276 =item B<Parameters:>
6280 The first argument (-name) is required and specifies the name of this
6285 The second argument (-src) is also required and specifies the URL
6288 The third option (-align, optional) is an alignment type, and may be
6289 TOP, BOTTOM or MIDDLE
6293 Fetch the value of the button this way:
6294 $x = $query->param('button_name.x');
6295 $y = $query->param('button_name.y');
6297 =head2 CREATING A JAVASCRIPT ACTION BUTTON
6299 print $query->button(-name=>'button_name',
6300 -value=>'user visible label',
6301 -onClick=>"do_something()");
6305 print $query->button('button_name',"do_something()");
6307 button() produces a button that is compatible with Netscape 2.0's
6308 JavaScript. When it's pressed the fragment of JavaScript code
6309 pointed to by the B<-onClick> parameter will be executed. On
6310 non-Netscape browsers this form element will probably not even
6315 Netscape browsers versions 1.1 and higher, and all versions of
6316 Internet Explorer, support a so-called "cookie" designed to help
6317 maintain state within a browser session. CGI.pm has several methods
6318 that support cookies.
6320 A cookie is a name=value pair much like the named parameters in a CGI
6321 query string. CGI scripts create one or more cookies and send
6322 them to the browser in the HTTP header. The browser maintains a list
6323 of cookies that belong to a particular Web server, and returns them
6324 to the CGI script during subsequent interactions.
6326 In addition to the required name=value pair, each cookie has several
6327 optional attributes:
6331 =item 1. an expiration time
6333 This is a time/date string (in a special GMT format) that indicates
6334 when a cookie expires. The cookie will be saved and returned to your
6335 script until this expiration date is reached if the user exits
6336 the browser and restarts it. If an expiration date isn't specified, the cookie
6337 will remain active until the user quits the browser.
6341 This is a partial or complete domain name for which the cookie is
6342 valid. The browser will return the cookie to any host that matches
6343 the partial domain name. For example, if you specify a domain name
6344 of ".capricorn.com", then the browser will return the cookie to
6345 Web servers running on any of the machines "www.capricorn.com",
6346 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
6347 must contain at least two periods to prevent attempts to match
6348 on top level domains like ".edu". If no domain is specified, then
6349 the browser will only return the cookie to servers on the host the
6350 cookie originated from.
6354 If you provide a cookie path attribute, the browser will check it
6355 against your script's URL before returning the cookie. For example,
6356 if you specify the path "/cgi-bin", then the cookie will be returned
6357 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
6358 and "/cgi-bin/customer_service/complain.pl", but not to the script
6359 "/cgi-private/site_admin.pl". By default, path is set to "/", which
6360 causes the cookie to be sent to any CGI script on your site.
6362 =item 4. a "secure" flag
6364 If the "secure" attribute is set, the cookie will only be sent to your
6365 script if the CGI request is occurring on a secure channel, such as SSL.
6369 The interface to HTTP cookies is the B<cookie()> method:
6371 $cookie = $query->cookie(-name=>'sessionID',
6374 -path=>'/cgi-bin/database',
6375 -domain=>'.capricorn.org',
6377 print $query->header(-cookie=>$cookie);
6379 B<cookie()> creates a new cookie. Its parameters include:
6385 The name of the cookie (required). This can be any string at all.
6386 Although browsers limit their cookie names to non-whitespace
6387 alphanumeric characters, CGI.pm removes this restriction by escaping
6388 and unescaping cookies behind the scenes.
6392 The value of the cookie. This can be any scalar value,
6393 array reference, or even associative array reference. For example,
6394 you can store an entire associative array into a cookie this way:
6396 $cookie=$query->cookie(-name=>'family information',
6397 -value=>\%childrens_ages);
6401 The optional partial path for which this cookie will be valid, as described
6406 The optional partial domain for which this cookie will be valid, as described
6411 The optional expiration date for this cookie. The format is as described
6412 in the section on the B<header()> method:
6414 "+1h" one hour from now
6418 If set to true, this cookie will only be used within a secure
6423 The cookie created by cookie() must be incorporated into the HTTP
6424 header within the string returned by the header() method:
6426 print $query->header(-cookie=>$my_cookie);
6428 To create multiple cookies, give header() an array reference:
6430 $cookie1 = $query->cookie(-name=>'riddle_name',
6431 -value=>"The Sphynx's Question");
6432 $cookie2 = $query->cookie(-name=>'answers',
6434 print $query->header(-cookie=>[$cookie1,$cookie2]);
6436 To retrieve a cookie, request it by name by calling cookie() method
6437 without the B<-value> parameter:
6441 $riddle = $query->cookie('riddle_name');
6442 %answers = $query->cookie('answers');
6444 Cookies created with a single scalar value, such as the "riddle_name"
6445 cookie, will be returned in that form. Cookies with array and hash
6446 values can also be retrieved.
6448 The cookie and CGI namespaces are separate. If you have a parameter
6449 named 'answers' and a cookie named 'answers', the values retrieved by
6450 param() and cookie() are independent of each other. However, it's
6451 simple to turn a CGI parameter into a cookie, and vice-versa:
6453 # turn a CGI parameter into a cookie
6454 $c=$q->cookie(-name=>'answers',-value=>[$q->param('answers')]);
6456 $q->param(-name=>'answers',-value=>[$q->cookie('answers')]);
6458 See the B<cookie.cgi> example script for some ideas on how to use
6459 cookies effectively.
6461 =head1 WORKING WITH FRAMES
6463 It's possible for CGI.pm scripts to write into several browser panels
6464 and windows using the HTML 4 frame mechanism. There are three
6465 techniques for defining new frames programmatically:
6469 =item 1. Create a <Frameset> document
6471 After writing out the HTTP header, instead of creating a standard
6472 HTML document using the start_html() call, create a <frameset>
6473 document that defines the frames on the page. Specify your script(s)
6474 (with appropriate parameters) as the SRC for each of the frames.
6476 There is no specific support for creating <frameset> sections
6477 in CGI.pm, but the HTML is very simple to write. See the frame
6478 documentation in Netscape's home pages for details
6480 http://home.netscape.com/assist/net_sites/frames.html
6482 =item 2. Specify the destination for the document in the HTTP header
6484 You may provide a B<-target> parameter to the header() method:
6486 print $q->header(-target=>'ResultsWindow');
6488 This will tell the browser to load the output of your script into the
6489 frame named "ResultsWindow". If a frame of that name doesn't already
6490 exist, the browser will pop up a new window and load your script's
6491 document into that. There are a number of magic names that you can
6492 use for targets. See the frame documents on Netscape's home pages for
6495 =item 3. Specify the destination for the document in the <form> tag
6497 You can specify the frame to load in the FORM tag itself. With
6498 CGI.pm it looks like this:
6500 print $q->start_form(-target=>'ResultsWindow');
6502 When your script is reinvoked by the form, its output will be loaded
6503 into the frame named "ResultsWindow". If one doesn't already exist
6504 a new window will be created.
6508 The script "frameset.cgi" in the examples directory shows one way to
6509 create pages in which the fill-out form and the response live in
6510 side-by-side frames.
6512 =head1 LIMITED SUPPORT FOR CASCADING STYLE SHEETS
6514 CGI.pm has limited support for HTML3's cascading style sheets (css).
6515 To incorporate a stylesheet into your document, pass the
6516 start_html() method a B<-style> parameter. The value of this
6517 parameter may be a scalar, in which case it is treated as the source
6518 URL for the stylesheet, or it may be a hash reference. In the latter
6519 case you should provide the hash with one or more of B<-src> or
6520 B<-code>. B<-src> points to a URL where an externally-defined
6521 stylesheet can be found. B<-code> points to a scalar value to be
6522 incorporated into a <style> section. Style definitions in B<-code>
6523 override similarly-named ones in B<-src>, hence the name "cascading."
6525 You may also specify the type of the stylesheet by adding the optional
6526 B<-type> parameter to the hash pointed to by B<-style>. If not
6527 specified, the style defaults to 'text/css'.
6529 To refer to a style within the body of your document, add the
6530 B<-class> parameter to any HTML element:
6532 print h1({-class=>'Fancy'},'Welcome to the Party');
6534 Or define styles on the fly with the B<-style> parameter:
6536 print h1({-style=>'Color: red;'},'Welcome to Hell');
6538 You may also use the new B<span()> element to apply a style to a
6541 print span({-style=>'Color: red;'},
6542 h1('Welcome to Hell'),
6543 "Where did that handbasket get to?"
6546 Note that you must import the ":html3" definitions to have the
6547 B<span()> method available. Here's a quick and dirty example of using
6548 CSS's. See the CSS specification at
6549 http://www.w3.org/pub/WWW/TR/Wd-css-1.html for more information.
6551 use CGI qw/:standard :html3/;
6553 #here's a stylesheet incorporated directly into the page
6563 font-family: sans-serif;
6569 print start_html( -title=>'CGI with Style',
6570 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
6573 print h1('CGI with Style'),
6575 "Better read the cascading style sheet spec before playing with this!"),
6576 span({-style=>'color: magenta'},
6577 "Look Mom, no hands!",
6583 Pass an array reference to B<-style> in order to incorporate multiple
6584 stylesheets into your document.
6586 Should you wish to incorporate a verbatim stylesheet that includes
6587 arbitrary formatting in the header, you may pass a -verbatim tag to
6588 the -style hash, as follows:
6590 print $q->start_html (-STYLE => {-verbatim => '@import
6591 url("/server-common/css/'.$cssFile.'");',
6592 -src => '/server-common/css/core.css'});
6596 This will generate an HTML header that contains this:
6598 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
6599 <style type="text/css">
6600 @import url("/server-common/css/main.css");
6603 Any additional arguments passed in the -style value will be
6604 incorporated into the <link> tag. For example:
6606 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
6611 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
6612 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
6616 To make more complicated <link> tags, use the Link() function
6617 and pass it to start_html() in the -head argument, as in:
6619 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
6620 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
6621 print start_html({-head=>\@h})
6625 If you are running the script from the command line or in the perl
6626 debugger, you can pass the script a list of keywords or
6627 parameter=value pairs on the command line or from standard input (you
6628 don't have to worry about tricking your script into reading from
6629 environment variables). You can pass keywords like this:
6631 your_script.pl keyword1 keyword2 keyword3
6635 your_script.pl keyword1+keyword2+keyword3
6639 your_script.pl name1=value1 name2=value2
6643 your_script.pl name1=value1&name2=value2
6645 To turn off this feature, use the -no_debug pragma.
6647 To test the POST method, you may enable full debugging with the -debug
6648 pragma. This will allow you to feed newline-delimited name=value
6649 pairs to the script on standard input.
6651 When debugging, you can use quotes and backslashes to escape
6652 characters in the familiar shell manner, letting you place
6653 spaces and other funny characters in your parameter=value
6656 your_script.pl "name1='I am a long value'" "name2=two\ words"
6658 Finally, you can set the path info for the script by prefixing the first
6659 name/value parameter with the path followed by a question mark (?):
6661 your_script.pl /your/path/here?name1=value1&name2=value2
6663 =head2 DUMPING OUT ALL THE NAME/VALUE PAIRS
6665 The Dump() method produces a string consisting of all the query's
6666 name/value pairs formatted nicely as a nested list. This is useful
6667 for debugging purposes:
6672 Produces something that looks like:
6686 As a shortcut, you can interpolate the entire CGI object into a string
6687 and it will be replaced with the a nice HTML dump shown above:
6690 print "<h2>Current Values</h2> $query\n";
6692 =head1 FETCHING ENVIRONMENT VARIABLES
6694 Some of the more useful environment variables can be fetched
6695 through this interface. The methods are as follows:
6701 Return a list of MIME types that the remote browser accepts. If you
6702 give this method a single argument corresponding to a MIME type, as in
6703 $query->Accept('text/html'), it will return a floating point value
6704 corresponding to the browser's preference for this type from 0.0
6705 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
6706 list are handled correctly.
6708 Note that the capitalization changed between version 2.43 and 2.44 in
6709 order to avoid conflict with Perl's accept() function.
6711 =item B<raw_cookie()>
6713 Returns the HTTP_COOKIE variable, an HTTP extension implemented by
6714 Netscape browsers version 1.1 and higher, and all versions of Internet
6715 Explorer. Cookies have a special format, and this method call just
6716 returns the raw form (?cookie dough). See cookie() for ways of
6717 setting and retrieving cooked cookies.
6719 Called with no parameters, raw_cookie() returns the packed cookie
6720 structure. You can separate it into individual cookies by splitting
6721 on the character sequence "; ". Called with the name of a cookie,
6722 retrieves the B<unescaped> form of the cookie. You can use the
6723 regular cookie() method to get the names, or use the raw_fetch()
6724 method from the CGI::Cookie module.
6726 =item B<user_agent()>
6728 Returns the HTTP_USER_AGENT variable. If you give
6729 this method a single argument, it will attempt to
6730 pattern match on it, allowing you to do something
6731 like $query->user_agent(netscape);
6733 =item B<path_info()>
6735 Returns additional path information from the script URL.
6736 E.G. fetching /cgi-bin/your_script/additional/stuff will result in
6737 $query->path_info() returning "/additional/stuff".
6739 NOTE: The Microsoft Internet Information Server
6740 is broken with respect to additional path information. If
6741 you use the Perl DLL library, the IIS server will attempt to
6742 execute the additional path information as a Perl script.
6743 If you use the ordinary file associations mapping, the
6744 path information will be present in the environment,
6745 but incorrect. The best thing to do is to avoid using additional
6746 path information in CGI scripts destined for use with IIS.
6748 =item B<path_translated()>
6750 As per path_info() but returns the additional
6751 path information translated into a physical path, e.g.
6752 "/usr/local/etc/httpd/htdocs/additional/stuff".
6754 The Microsoft IIS is broken with respect to the translated
6757 =item B<remote_host()>
6759 Returns either the remote host name or IP address.
6760 if the former is unavailable.
6762 =item B<script_name()>
6763 Return the script name as a partial URL, for self-refering
6768 Return the URL of the page the browser was viewing
6769 prior to fetching your script. Not available for all
6772 =item B<auth_type ()>
6774 Return the authorization/verification method in use for this
6777 =item B<server_name ()>
6779 Returns the name of the server, usually the machine's host
6782 =item B<virtual_host ()>
6784 When using virtual hosts, returns the name of the host that
6785 the browser attempted to contact
6787 =item B<server_port ()>
6789 Return the port that the server is listening on.
6791 =item B<virtual_port ()>
6793 Like server_port() except that it takes virtual hosts into account.
6794 Use this when running with virtual hosts.
6796 =item B<server_software ()>
6798 Returns the server software and version number.
6800 =item B<remote_user ()>
6802 Return the authorization/verification name used for user
6803 verification, if this script is protected.
6805 =item B<user_name ()>
6807 Attempt to obtain the remote user's name, using a variety of different
6808 techniques. This only works with older browsers such as Mosaic.
6809 Newer browsers do not report the user name for privacy reasons!
6811 =item B<request_method()>
6813 Returns the method used to access your script, usually
6814 one of 'POST', 'GET' or 'HEAD'.
6816 =item B<content_type()>
6818 Returns the content_type of data submitted in a POST, generally
6819 multipart/form-data or application/x-www-form-urlencoded
6823 Called with no arguments returns the list of HTTP environment
6824 variables, including such things as HTTP_USER_AGENT,
6825 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
6826 like-named HTTP header fields in the request. Called with the name of
6827 an HTTP header field, returns its value. Capitalization and the use
6828 of hyphens versus underscores are not significant.
6830 For example, all three of these examples are equivalent:
6832 $requested_language = $q->http('Accept-language');
6833 $requested_language = $q->http('Accept_language');
6834 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
6838 The same as I<http()>, but operates on the HTTPS environment variables
6839 present when the SSL protocol is in effect. Can be used to determine
6840 whether SSL is turned on.
6844 =head1 USING NPH SCRIPTS
6846 NPH, or "no-parsed-header", scripts bypass the server completely by
6847 sending the complete HTTP header directly to the browser. This has
6848 slight performance benefits, but is of most use for taking advantage
6849 of HTTP extensions that are not directly supported by your server,
6850 such as server push and PICS headers.
6852 Servers use a variety of conventions for designating CGI scripts as
6853 NPH. Many Unix servers look at the beginning of the script's name for
6854 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
6855 Internet Information Server, in contrast, try to decide whether a
6856 program is an NPH script by examining the first line of script output.
6859 CGI.pm supports NPH scripts with a special NPH mode. When in this
6860 mode, CGI.pm will output the necessary extra header information when
6861 the header() and redirect() methods are
6864 The Microsoft Internet Information Server requires NPH mode. As of
6865 version 2.30, CGI.pm will automatically detect when the script is
6866 running under IIS and put itself into this mode. You do not need to
6867 do this manually, although it won't hurt anything if you do. However,
6868 note that if you have applied Service Pack 6, much of the
6869 functionality of NPH scripts, including the ability to redirect while
6870 setting a cookie, b<do not work at all> on IIS without a special patch
6872 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
6873 Non-Parsed Headers Stripped From CGI Applications That Have nph-
6878 =item In the B<use> statement
6880 Simply add the "-nph" pragmato the list of symbols to be imported into
6883 use CGI qw(:standard -nph)
6885 =item By calling the B<nph()> method:
6887 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
6891 =item By using B<-nph> parameters
6893 in the B<header()> and B<redirect()> statements:
6895 print $q->header(-nph=>1);
6901 CGI.pm provides four simple functions for producing multipart
6902 documents of the type needed to implement server push. These
6903 functions were graciously provided by Ed Jordan <ed@fidalgo.net>. To
6904 import these into your namespace, you must import the ":push" set.
6905 You are also advised to put the script into NPH mode and to set $| to
6906 1 to avoid buffering problems.
6908 Here is a simple script that demonstrates server push:
6910 #!/usr/local/bin/perl
6911 use CGI qw/:push -nph/;
6913 print multipart_init(-boundary=>'----here we go!');
6915 print multipart_start(-type=>'text/plain'),
6916 "The current time is ",scalar(localtime),"\n";
6918 print multipart_end;
6920 print multipart_final;
6925 This script initializes server push by calling B<multipart_init()>.
6926 It then enters a loop in which it begins a new multipart section by
6927 calling B<multipart_start()>, prints the current local time,
6928 and ends a multipart section with B<multipart_end()>. It then sleeps
6929 a second, and begins again. On the final iteration, it ends the
6930 multipart section with B<multipart_final()> rather than with
6935 =item multipart_init()
6937 multipart_init(-boundary=>$boundary);
6939 Initialize the multipart system. The -boundary argument specifies
6940 what MIME boundary string to use to separate parts of the document.
6941 If not provided, CGI.pm chooses a reasonable boundary for you.
6943 =item multipart_start()
6945 multipart_start(-type=>$type)
6947 Start a new part of the multipart document using the specified MIME
6948 type. If not specified, text/html is assumed.
6950 =item multipart_end()
6954 End a part. You must remember to call multipart_end() once for each
6955 multipart_start(), except at the end of the last part of the multipart
6956 document when multipart_final() should be called instead of multipart_end().
6958 =item multipart_final()
6962 End all parts. You should call multipart_final() rather than
6963 multipart_end() at the end of the last part of the multipart document.
6967 Users interested in server push applications should also have a look
6968 at the CGI::Push module.
6970 Only Netscape Navigator supports server push. Internet Explorer
6973 =head1 Avoiding Denial of Service Attacks
6975 A potential problem with CGI.pm is that, by default, it attempts to
6976 process form POSTings no matter how large they are. A wily hacker
6977 could attack your site by sending a CGI script a huge POST of many
6978 megabytes. CGI.pm will attempt to read the entire POST into a
6979 variable, growing hugely in size until it runs out of memory. While
6980 the script attempts to allocate the memory the system may slow down
6981 dramatically. This is a form of denial of service attack.
6983 Another possible attack is for the remote user to force CGI.pm to
6984 accept a huge file upload. CGI.pm will accept the upload and store it
6985 in a temporary directory even if your script doesn't expect to receive
6986 an uploaded file. CGI.pm will delete the file automatically when it
6987 terminates, but in the meantime the remote user may have filled up the
6988 server's disk space, causing problems for other programs.
6990 The best way to avoid denial of service attacks is to limit the amount
6991 of memory, CPU time and disk space that CGI scripts can use. Some Web
6992 servers come with built-in facilities to accomplish this. In other
6993 cases, you can use the shell I<limit> or I<ulimit>
6994 commands to put ceilings on CGI resource usage.
6997 CGI.pm also has some simple built-in protections against denial of
6998 service attacks, but you must activate them before you can use them.
6999 These take the form of two global variables in the CGI name space:
7003 =item B<$CGI::POST_MAX>
7005 If set to a non-negative integer, this variable puts a ceiling
7006 on the size of POSTings, in bytes. If CGI.pm detects a POST
7007 that is greater than the ceiling, it will immediately exit with an error
7008 message. This value will affect both ordinary POSTs and
7009 multipart POSTs, meaning that it limits the maximum size of file
7010 uploads as well. You should set this to a reasonably high
7011 value, such as 1 megabyte.
7013 =item B<$CGI::DISABLE_UPLOADS>
7015 If set to a non-zero value, this will disable file uploads
7016 completely. Other fill-out form values will work as usual.
7020 You can use these variables in either of two ways.
7024 =item B<1. On a script-by-script basis>
7026 Set the variable at the top of the script, right after the "use" statement:
7028 use CGI qw/:standard/;
7029 use CGI::Carp 'fatalsToBrowser';
7030 $CGI::POST_MAX=1024 * 100; # max 100K posts
7031 $CGI::DISABLE_UPLOADS = 1; # no uploads
7033 =item B<2. Globally for all scripts>
7035 Open up CGI.pm, find the definitions for $POST_MAX and
7036 $DISABLE_UPLOADS, and set them to the desired values. You'll
7037 find them towards the top of the file in a subroutine named
7038 initialize_globals().
7042 An attempt to send a POST larger than $POST_MAX bytes will cause
7043 I<param()> to return an empty CGI parameter list. You can test for
7044 this event by checking I<cgi_error()>, either after you create the CGI
7045 object or, if you are using the function-oriented interface, call
7046 <param()> for the first time. If the POST was intercepted, then
7047 cgi_error() will return the message "413 POST too large".
7049 This error message is actually defined by the HTTP protocol, and is
7050 designed to be returned to the browser as the CGI script's status
7053 $uploaded_file = param('upload');
7054 if (!$uploaded_file && cgi_error()) {
7055 print header(-status=>cgi_error());
7059 However it isn't clear that any browser currently knows what to do
7060 with this status code. It might be better just to create an
7061 HTML page that warns the user of the problem.
7063 =head1 COMPATIBILITY WITH CGI-LIB.PL
7065 To make it easier to port existing programs that use cgi-lib.pl the
7066 compatibility routine "ReadParse" is provided. Porting is simple:
7069 require "cgi-lib.pl";
7071 print "The value of the antique is $in{antique}.\n";
7076 print "The value of the antique is $in{antique}.\n";
7078 CGI.pm's ReadParse() routine creates a tied variable named %in,
7079 which can be accessed to obtain the query variables. Like
7080 ReadParse, you can also provide your own variable. Infrequently
7081 used features of ReadParse, such as the creation of @in and $in
7082 variables, are not supported.
7084 Once you use ReadParse, you can retrieve the query object itself
7088 print $q->textfield(-name=>'wow',
7089 -value=>'does this really work?');
7091 This allows you to start using the more interesting features
7092 of CGI.pm without rewriting your old scripts from scratch.
7094 =head1 AUTHOR INFORMATION
7096 Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
7098 This library is free software; you can redistribute it and/or modify
7099 it under the same terms as Perl itself.
7101 Address bug reports and comments to: lstein@cshl.org. When sending
7102 bug reports, please provide the version of CGI.pm, the version of
7103 Perl, the name and version of your Web server, and the name and
7104 version of the operating system you are using. If the problem is even
7105 remotely browser dependent, please provide information about the
7106 affected browers as well.
7110 Thanks very much to:
7114 =item Matt Heffron (heffron@falstaff.css.beckman.com)
7116 =item James Taylor (james.taylor@srs.gov)
7118 =item Scott Anguish <sanguish@digifix.com>
7120 =item Mike Jewell (mlj3u@virginia.edu)
7122 =item Timothy Shimmin (tes@kbs.citri.edu.au)
7124 =item Joergen Haegg (jh@axis.se)
7126 =item Laurent Delfosse (delfosse@delfosse.com)
7128 =item Richard Resnick (applepi1@aol.com)
7130 =item Craig Bishop (csb@barwonwater.vic.gov.au)
7132 =item Tony Curtis (tc@vcpc.univie.ac.at)
7134 =item Tim Bunce (Tim.Bunce@ig.co.uk)
7136 =item Tom Christiansen (tchrist@convex.com)
7138 =item Andreas Koenig (k@franz.ww.TU-Berlin.DE)
7140 =item Tim MacKenzie (Tim.MacKenzie@fulcrum.com.au)
7142 =item Kevin B. Hendricks (kbhend@dogwood.tyler.wm.edu)
7144 =item Stephen Dahmen (joyfire@inxpress.net)
7146 =item Ed Jordan (ed@fidalgo.net)
7148 =item David Alan Pisoni (david@cnation.com)
7150 =item Doug MacEachern (dougm@opengroup.org)
7152 =item Robin Houston (robin@oneworld.org)
7154 =item ...and many many more...
7156 for suggestions and bug fixes.
7160 =head1 A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT
7163 #!/usr/local/bin/perl
7169 print $query->header;
7170 print $query->start_html("Example CGI.pm Form");
7171 print "<h1> Example CGI.pm Form</h1>\n";
7172 &print_prompt($query);
7175 print $query->end_html;
7180 print $query->start_form;
7181 print "<em>What's your name?</em><br>";
7182 print $query->textfield('name');
7183 print $query->checkbox('Not my real name');
7185 print "<p><em>Where can you find English Sparrows?</em><br>";
7186 print $query->checkbox_group(
7187 -name=>'Sparrow locations',
7188 -values=>[England,France,Spain,Asia,Hoboken],
7190 -defaults=>[England,Asia]);
7192 print "<p><em>How far can they fly?</em><br>",
7193 $query->radio_group(
7195 -values=>['10 ft','1 mile','10 miles','real far'],
7196 -default=>'1 mile');
7198 print "<p><em>What's your favorite color?</em> ";
7199 print $query->popup_menu(-name=>'Color',
7200 -values=>['black','brown','red','yellow'],
7203 print $query->hidden('Reference','Monty Python and the Holy Grail');
7205 print "<p><em>What have you got there?</em><br>";
7206 print $query->scrolling_list(
7207 -name=>'possessions',
7208 -values=>['A Coconut','A Grail','An Icon',
7209 'A Sword','A Ticket'],
7213 print "<p><em>Any parting comments?</em><br>";
7214 print $query->textarea(-name=>'Comments',
7218 print "<p>",$query->reset;
7219 print $query->submit('Action','Shout');
7220 print $query->submit('Action','Scream');
7221 print $query->endform;
7229 print "<h2>Here are the current settings in this form</h2>";
7231 foreach $key ($query->param) {
7232 print "<strong>$key</strong> -> ";
7233 @values = $query->param($key);
7234 print join(", ",@values),"<br>\n";
7241 <address>Lincoln D. Stein</address><br>
7242 <a href="/">Home Page</a>
7252 L<CGI::Carp>, L<CGI::Fast>, L<CGI::Pretty>