5 # this module is both strict (and warnings) compliant, but they are only used
6 # in testing as they add an unnecessary compile time overhead in production.
11 $VERSION $USE_CGI_PM_DEFAULTS $DISABLE_UPLOADS $POST_MAX
12 $NO_UNDEF_PARAMS $USE_PARAM_SEMICOLONS $PARAM_UTF8 $HEADERS_ONCE
13 $NPH $DEBUG $NO_NULL $FATAL *in
18 # you can hard code the global variable settings here if you want.
19 # warning - do not delete the unless defined $VAR part unless you
20 # want to permanently remove the ability to change the variable.
21 sub _initialize_globals {
23 # set this to 1 to use CGI.pm default global settings
24 $USE_CGI_PM_DEFAULTS = 0
25 unless defined $USE_CGI_PM_DEFAULTS;
27 # see if user wants old CGI.pm defaults
28 if ( $USE_CGI_PM_DEFAULTS ) {
29 _use_cgi_pm_global_settings();
33 # no file uploads by default, set to 0 to enable uploads
35 unless defined $DISABLE_UPLOADS;
37 # use a post max of 100K, set to -1 for no limits
39 unless defined $POST_MAX;
41 # set to 1 to not include undefined params parsed from query string
43 unless defined $NO_UNDEF_PARAMS;
45 # separate the name=value pairs with ; rather than &
46 $USE_PARAM_SEMICOLONS = 0
47 unless defined $USE_PARAM_SEMICOLONS;
49 # return everything as utf-8
51 $PARAM_UTF8 and require Encode;
53 # only print headers once
55 unless defined $HEADERS_ONCE;
57 # Set this to 1 to enable NPH scripts
61 # 0 => no debug, 1 => from @ARGV, 2 => from STDIN
63 unless defined $DEBUG;
65 # filter out null bytes in param - value pairs
67 unless defined $NO_NULL;
69 # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak
71 unless defined $FATAL;
74 # I happen to disagree with many of the default global settings in CGI.pm
75 # This sub is called if you set $CGI::Simple::USE_CGI_PM_GLOBALS = 1; or
76 # invoke the '-default' pragma via a use CGI::Simple qw(-default);
77 sub _use_cgi_pm_global_settings {
78 $USE_CGI_PM_DEFAULTS = 1;
79 $DISABLE_UPLOADS = 0 unless defined $DISABLE_UPLOADS;
80 $POST_MAX = -1 unless defined $POST_MAX;
81 $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS;
82 $USE_PARAM_SEMICOLONS = 1 unless defined $USE_PARAM_SEMICOLONS;
83 $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE;
84 $NPH = 0 unless defined $NPH;
85 $DEBUG = 1 unless defined $DEBUG;
86 $NO_NULL = 0 unless defined $NO_NULL;
87 $FATAL = -1 unless defined $FATAL;
88 $PARAM_UTF8 = 0 unless defined $PARAM_UTF8;
91 # this is called by new, we will never directly reference the globals again
95 $self->{'.globals'}->{'DISABLE_UPLOADS'} = $DISABLE_UPLOADS;
96 $self->{'.globals'}->{'POST_MAX'} = $POST_MAX;
97 $self->{'.globals'}->{'NO_UNDEF_PARAMS'} = $NO_UNDEF_PARAMS;
98 $self->{'.globals'}->{'USE_PARAM_SEMICOLONS'} = $USE_PARAM_SEMICOLONS;
99 $self->{'.globals'}->{'HEADERS_ONCE'} = $HEADERS_ONCE;
100 $self->{'.globals'}->{'NPH'} = $NPH;
101 $self->{'.globals'}->{'DEBUG'} = $DEBUG;
102 $self->{'.globals'}->{'NO_NULL'} = $NO_NULL;
103 $self->{'.globals'}->{'FATAL'} = $FATAL;
104 $self->{'.globals'}->{'USE_CGI_PM_DEFAULTS'} = $USE_CGI_PM_DEFAULTS;
105 $self->{'.globals'}->{'PARAM_UTF8'} = $PARAM_UTF8;
108 # use the automatic calling of the import sub to set our pragmas. CGI.pm compat
110 my ( $self, @args ) = @_;
112 # arguments supplied in the 'use CGI::Simple [ARGS];' will now be in @args
114 $USE_CGI_PM_DEFAULTS = 1, next if m/^-default/i;
115 $DISABLE_UPLOADS = 1, next if m/^-no.?upload/i;
116 $DISABLE_UPLOADS = 0, next if m/^-upload/i;
117 $HEADERS_ONCE = 1, next if m/^-unique.?header/i;
118 $NPH = 1, next if m/^-nph/i;
119 $DEBUG = 0, next if m/^-no.?debug/i;
120 $DEBUG = defined $1 ? $1 : 2, next if m/^-debug(\d)?/i;
121 $USE_PARAM_SEMICOLONS = 1, next if m/^-newstyle.?url/i;
122 $USE_PARAM_SEMICOLONS = 0, next if m/^-oldstyle.?url/i;
123 $NO_UNDEF_PARAMS = 1, next if m/^-no.?undef.?param/i;
124 $FATAL = 0, next if m/^-carp/i;
125 $FATAL = 1, next if m/^-croak/i;
126 croak "Pragma '$_' is not defined in CGI::Simple\n";
130 # used in CGI.pm .t files
132 _use_cgi_pm_global_settings();
138 # use correct encoding conversion to handle non ASCII char sets.
139 # we import and install the complex routines only if we have to.
143 my ( $self, $decode ) = @_;
144 return () unless defined $decode;
146 $decode =~ s/%([a-fA-F0-9]{2})/ pack "C", hex $1 /eg;
151 my ( $self, $encode ) = @_;
152 return () unless defined $encode;
154 =~ s/([^A-Za-z0-9\-_.!~*'() ])/ uc sprintf "%%%02x",ord $1 /eg;
159 if ( "\t" ne "\011" ) {
160 eval { require CGI::Simple::Util };
163 "Your server is using not using ASCII, you must install CGI::Simple::Util, error: $@";
166 # hack the symbol table and replace simple encode/decode subs
167 *CGI::Simple::url_encode
168 = sub { CGI::Simple::Util::escape( $_[1] ) };
169 *CGI::Simple::url_decode
170 = sub { CGI::Simple::Util::unescape( $_[1] ) };
174 ################ The Guts ################
177 my ( $class, $init ) = @_;
178 $class = ref( $class ) || $class;
181 if ( $self->_mod_perl ) {
183 $self->{'.mod_perl_request'} = $init;
184 undef $init; # otherwise _initialize takes the wrong path
186 $self->_initialize_mod_perl();
188 $self->_initialize_globals;
189 $self->_store_globals;
190 $self->_initialize( $init );
196 exists $ENV{MOD_PERL}
197 or ( $ENV{GATEWAY_INTERFACE}
198 and $ENV{GATEWAY_INTERFACE} =~ m{^CGI-Perl/} )
202 # Return the global request object under mod_perl. If you use mod_perl 2
203 # and you don't set PerlOptions +GlobalRequest then the request must be
204 # passed in to the new() method.
205 sub _mod_perl_request {
208 my $mp = $self->{'.mod_perl'};
212 my $req = $self->{'.mod_perl_request'};
215 $self->{'.mod_perl_request'} = do {
217 Apache2::RequestUtil->request;
225 sub _initialize_mod_perl {
228 eval "require mod_perl";
230 if ( defined $mod_perl::VERSION ) {
232 if ( $mod_perl::VERSION >= 2.00 ) {
233 $self->{'.mod_perl'} = 2;
235 require Apache2::RequestRec;
236 require Apache2::RequestIO;
237 require Apache2::RequestUtil;
238 require Apache2::Response;
241 my $r = $self->_mod_perl_request();
244 $r->subprocess_env unless exists $ENV{REQUEST_METHOD};
245 $r->pool->cleanup_register(
246 \&CGI::Simple::_initialize_globals );
250 $self->{'.mod_perl'} = 1;
254 my $r = $self->_mod_perl_request();
257 $r->register_cleanup( \&CGI::Simple::_initialize_globals );
264 my ( $self, $init ) = @_;
266 if ( !defined $init ) {
268 # initialize from QUERY_STRING, STDIN or @ARGV
269 $self->_read_parse();
271 elsif ( ( ref $init ) =~ m/HASH/i ) {
273 # initialize from param hash
274 for my $param ( keys %{$init} ) {
275 $self->_add_param( $param, $init->{$param} );
279 # chromatic's blessed GLOB patch
280 # elsif ( (ref $init) =~ m/GLOB/i ) { # initialize from a file
281 elsif ( UNIVERSAL::isa( $init, 'GLOB' ) ) { # initialize from a file
282 $self->_read_parse( $init );
284 elsif ( ( ref $init ) eq 'CGI::Simple' ) {
286 # initialize from a CGI::Simple object
287 require Data::Dumper;
289 # avoid problems with strict when Data::Dumper returns $VAR1
291 my $clone = eval( Data::Dumper::Dumper( $init ) );
293 $self->cgi_error( "Can't clone CGI::Simple object: $@" );
300 $self->_parse_params( $init ); # initialize from a query string
304 sub _internal_read($*\$;$) {
305 my ( $self, $glob, $buffer, $len ) = @_;
306 $len = 4096 if !defined $len;
307 if ( $self->{'.mod_perl'} ) {
308 my $r = $self->_mod_perl_request();
309 $r->read( $$buffer, $len );
312 read( $glob, $$buffer, $len );
318 my $handle = shift || \*STDIN;
321 my $type = $ENV{'CONTENT_TYPE'} || 'No CONTENT_TYPE received';
322 my $length = $ENV{'CONTENT_LENGTH'} || 0;
323 my $method = $ENV{'REQUEST_METHOD'} || 'No REQUEST_METHOD received';
325 # first check POST_MAX Steve Purkis pointed out the previous bug
326 if ( ( $method eq 'POST' or $method eq "PUT" )
327 and $self->{'.globals'}->{'POST_MAX'} != -1
328 and $length > $self->{'.globals'}->{'POST_MAX'} ) {
330 "413 Request entity too large: $length bytes on STDIN exceeds \$POST_MAX!"
333 # silently discard data ??? better to just close the socket ???
334 while ( $length > 0 ) {
335 last unless _internal_read( $self, $handle, my $buffer );
336 $length -= length( $buffer );
342 if ( $length and $type =~ m|^multipart/form-data|i ) {
343 my $got_length = $self->_parse_multipart( $handle );
344 if ( $length != $got_length ) {
346 "500 Bad read on multipart/form-data! wanted $length, got $got_length"
352 elsif ( $method eq 'POST' or $method eq 'PUT' ) {
355 # we may not get all the data we want with a single read on large
356 # POSTs as it may not be here yet! Credit Jason Luther for patch
357 # CGI.pm < 2.99 suffers from same bug
358 _internal_read( $self, $handle, $data, $length );
359 while ( length( $data ) < $length ) {
360 last unless _internal_read( $self, $handle, my $buffer );
364 unless ( $length == length $data ) {
365 $self->cgi_error( "500 Bad read on POST! wanted $length, got "
370 if ( $type !~ m|^application/x-www-form-urlencoded| ) {
371 $self->_add_param( $method . "DATA", $data );
374 $self->_parse_params( $data );
378 elsif ( $method eq 'GET' or $method eq 'HEAD' ) {
380 = $self->{'.mod_perl'}
381 ? $self->_mod_perl_request()->args()
382 : $ENV{'QUERY_STRING'}
383 || $ENV{'REDIRECT_QUERY_STRING'}
385 $self->_parse_params( $data );
388 unless ( $self->{'.globals'}->{'DEBUG'}
389 and $data = $self->read_from_cmdline() ) {
390 $self->cgi_error( "400 Unknown method $method" );
396 # I liked this reporting but CGI.pm does not behave like this so
398 # $self->cgi_error("400 No data received via method: $method, type: $type");
402 $self->_parse_params( $data );
407 my ( $self, $data ) = @_;
408 return () unless defined $data;
409 unless ( $data =~ /[&=;]/ ) {
410 $self->{'keywords'} = [ $self->_parse_keywordlist( $data ) ];
413 my @pairs = split /[&;]/, $data;
414 for my $pair ( @pairs ) {
415 my ( $param, $value ) = split /=/, $pair, 2;
416 next unless defined $param;
417 $value = '' unless defined $value;
418 $self->_add_param( $self->url_decode( $param ),
419 $self->url_decode( $value ) );
424 my ( $self, $param, $value, $overwrite ) = @_;
425 return () unless defined $param and defined $value;
426 $param =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'};
427 @{ $self->{$param} } = () if $overwrite;
428 @{ $self->{$param} } = () unless exists $self->{$param};
429 my @values = ref $value ? @{$value} : ( $value );
430 for my $value ( @values ) {
433 and $self->{'.globals'}->{'NO_UNDEF_PARAMS'};
434 $value =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'};
435 $value = Encode::decode( utf8 => $value )
436 if $self->{'.globals'}->{PARAM_UTF8};
437 push @{ $self->{$param} }, $value;
438 unless ( $self->{'.fieldnames'}->{$param} ) {
439 push @{ $self->{'.parameters'} }, $param;
440 $self->{'.fieldnames'}->{$param}++;
443 return scalar @values; # for compatibility with CGI.pm request.t
446 sub _parse_keywordlist {
447 my ( $self, $data ) = @_;
448 return () unless defined $data;
449 $data = $self->url_decode( $data );
450 $data =~ tr/\000//d if $self->{'.globals'}->{'NO_NULL'};
451 my @keywords = split /\s+/, $data;
455 sub _massage_boundary {
456 my ( $self, $boundary ) = @_;
458 # BUG: IE 3.01 on the Macintosh uses just the boundary,
460 $boundary = '--' . $boundary
461 unless exists $ENV{'HTTP_USER_AGENT'}
462 && $ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+3\.0[12];\s*Mac/i;
464 return quotemeta $boundary;
467 sub _parse_multipart {
469 my $handle = shift or die "NEED A HANDLE!?";
472 = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/;
474 $boundary = $self->_massage_boundary( $boundary ) if $boundary;
478 my $length = $ENV{'CONTENT_LENGTH'} || 0;
479 my $CRLF = $self->crlf;
483 while ( $got_data < $length ) {
484 last READ unless _internal_read( $self, $handle, my $buffer );
486 $got_data += length $buffer;
488 unless ( $boundary ) {
489 # If we're going to guess the boundary we need a complete line.
490 next READ unless $data =~ /^(.*)$CRLF/o;
493 # Still no boundary? Give up...
494 unless ( $boundary ) {
496 '400 No boundary supplied for multipart/form-data' );
499 $boundary = $self->_massage_boundary( $boundary );
504 while ( $data =~ m/^$boundary$CRLF/ ) {
505 ## TAB and high ascii chars are definitivelly allowed in headers.
506 ## Not accepting them in the following regex prevents the upload of
507 ## files with filenames like "España.txt".
508 # next READ unless $data =~ m/^([\040-\176$CRLF]+?$CRLF$CRLF)/o;
510 unless $data =~ m/^([\x20-\x7E\x80-\xFF\x09$CRLF]+?$CRLF$CRLF)/o;
512 ( my $unfold = $1 ) =~ s/$CRLF\s+/ /og;
513 my ( $param ) = $unfold =~ m/form-data;\s+name="?([^\";]*)"?/;
515 = $unfold =~ m/name="?\Q$param\E"?;\s+filename="?([^\"]*)"?/;
517 if ( defined $filename ) {
518 my ( $mime ) = $unfold =~ m/Content-Type:\s+([-\w\/]+)/io;
519 $data =~ s/^\Q$header\E//;
520 ( $got_data, $data, my $fh, my $size )
521 = $self->_save_tmpfile( $handle, $boundary, $filename,
523 $self->_add_param( $param, $filename );
524 $self->{'.upload_fields'}->{$param} = $filename;
525 $self->{'.filehandles'}->{$filename} = $fh if $fh;
526 $self->{'.tmpfiles'}->{$filename}
527 = { 'size' => $size, 'mime' => $mime }
532 unless $data =~ s/^\Q$header\E(.*?)$CRLF(?=$boundary)//s;
533 $self->_add_param( $param, $1 );
535 unless ( $data =~ m/^$boundary/ ) {
536 ## In a perfect world, $data should always begin with $boundary.
537 ## But sometimes, IE5 prepends garbage boundaries into POST(ed) data.
538 ## Then, $data does not start with $boundary and the previous block
539 ## never gets executed. The following fix attempts to remove those
540 ## extra boundaries from readed $data and restart boundary parsing.
541 ## Note about performance: with well formed data, previous check is
542 ## executed (generally) only once, when $data value is "$boundary--"
543 ## at end of parsing.
544 goto BOUNDARY if ( $data =~ s/.*?$CRLF(?=$boundary$CRLF)//s );
551 my ( $self, $handle, $boundary, $filename, $got_data, $data ) = @_;
553 my $CRLF = $self->crlf;
554 my $length = $ENV{'CONTENT_LENGTH'} || 0;
556 if ( $self->{'.globals'}->{'DISABLE_UPLOADS'} ) {
557 $self->cgi_error( "405 Not Allowed - File uploads are disabled" );
559 elsif ( $filename ) {
560 eval { require IO::File };
561 $self->cgi_error( "500 IO::File is not available $@" ) if $@;
562 $fh = new_tmpfile IO::File;
563 $self->cgi_error( "500 IO::File can't create new temp_file" )
567 # read in data until closing boundary found. buffer to catch split boundary
568 # we do this regardless of whether we save the file or not to read the file
569 # data from STDIN. if either uploads are disabled or no file has been sent
570 # $fh will be undef so only do file stuff if $fh is true using $fh && syntax
572 while ( $got_data < $length ) {
575 last unless _internal_read( $self, \*STDIN, $data );
577 # fixed hanging bug if browser terminates upload part way through
578 # thanks to Brandon Black
581 '400 Malformed multipart, no terminating boundary' );
586 $got_data += length $data;
587 if ( "$buffer$data" =~ m/$boundary/ ) {
588 $data = $buffer . $data;
592 # we do not have partial boundary so print to file if valid $fh
593 $fh && print $fh $buffer;
594 $file_size += length $buffer;
596 $data =~ s/^(.*?)$CRLF(?=$boundary)//s;
597 $fh && print $fh $1; # print remainder of file if valid $fh
598 $file_size += length $1;
599 return $got_data, $data, $fh, $file_size;
602 # Define the CRLF sequence. You can't use a simple "\r\n" because of system
603 # specific 'features'. On EBCDIC systems "\t" ne "\011" as the don't use ASCII
605 my ( $self, $CRLF ) = @_;
606 $self->{'.crlf'} = $CRLF if $CRLF; # allow value to be set manually
607 unless ( $self->{'.crlf'} ) {
609 || do { require Config; $Config::Config{'osname'} };
611 = ( $OS =~ m/VMS/i ) ? "\n"
612 : ( "\t" ne "\011" ) ? "\r\n"
615 return $self->{'.crlf'};
618 ################ The Core Methods ################
621 my ( $self, $param, @p ) = @_;
622 unless ( defined $param ) { # return list of all params
624 = $self->{'.parameters'} ? @{ $self->{'.parameters'} } : ();
627 unless ( @p ) { # return values for $param
628 return () unless exists $self->{$param};
629 return wantarray ? @{ $self->{$param} } : $self->{$param}->[0];
631 if ( $param =~ m/^-name$/i and @p == 1 ) {
632 return () unless exists $self->{ $p[0] };
633 return wantarray ? @{ $self->{ $p[0] } } : $self->{ $p[0] }->[0];
636 # set values using -name=>'foo',-value=>'bar' syntax.
637 # also allows for $q->param( 'foo', 'some', 'new', 'values' ) syntax
638 ( $param, undef, @p ) = @p
639 if $param =~ m/^-name$/i; # undef represents -value token
640 $self->_add_param( $param, ( ref $p[0] eq 'ARRAY' ? $p[0] : [@p] ),
642 return wantarray ? @{ $self->{$param} } : $self->{$param}->[0];
645 # a new method that provides access to a new internal routine. Useage:
646 # $q->add_param( $param, $value, $overwrite )
647 # $param must be a plain scalar
648 # $value may be either a scalar or an array ref
649 # if $overwrite is a true value $param will be overwritten with new values.
655 my ( $self, $param, @p ) = @_;
657 = ( defined $param and $param =~ m/^-name$/i ) ? $p[0] : $param;
658 return undef unless defined $param;
659 $self->_add_param( $param, [] ) unless exists $self->{$param};
660 return $self->{$param};
663 # Return a parameter in the QUERY_STRING, regardless of whether a POST or GET
665 my ( $self, $param ) = @_;
666 return () unless $ENV{'QUERY_STRING'};
667 $self->{'.url_param'} = {};
668 bless $self->{'.url_param'}, 'CGI::Simple';
669 $self->{'.url_param'}->_parse_params( $ENV{'QUERY_STRING'} );
670 return $self->{'.url_param'}->param( $param );
674 my ( $self, @values ) = @_;
676 = ref $values[0] eq 'ARRAY' ? $values[0] : [@values]
679 = defined( $self->{'keywords'} ) ? @{ $self->{'keywords'} } : ();
685 $self->{'.sep'} = shift || $self->{'.sep'} || "\0";
687 for my $param ( $self->param ) {
688 $hash{$param} = join $self->{'.sep'}, $self->param( $param );
690 tie %tied, "CGI::Simple", $self;
691 return wantarray ? %hash : \%tied;
694 sub TIEHASH { $_[1] ? $_[1] : new $_[0] }
697 my ( $q, $p, $v ) = @_;
698 $q->param( $p, split $q->{'.sep'}, $v );
703 ref $q->{$p} eq "ARRAY" ? join $q->{'.sep'}, @{ $q->{$p} } : $q->{$p};
705 sub FIRSTKEY { my $a = scalar keys %{ $_[0] }; each %{ $_[0] } }
706 sub NEXTKEY { each %{ $_[0] } }
707 sub EXISTS { exists $_[0]->{ $_[1] } }
708 sub DELETE { $_[0]->delete( $_[1] ) }
709 sub CLEAR { %{ $_[0] } = () }
712 my ( $self, $param, @p ) = @_;
713 return () unless defined $param;
715 # set values using $q->append(-name=>'foo',-value=>'bar') syntax
716 # also allows for $q->append( 'foo', 'some', 'new', 'values' ) syntax
717 ( $param, undef, @p ) = @p
718 if $param =~ m/^-name$/i; # undef represents -value token
719 $self->_add_param( $param,
720 ( ( defined $p[0] and ref $p[0] ) ? $p[0] : [@p] ) );
721 return $self->param( $param );
725 my ( $self, $param ) = @_;
726 return () unless defined $param;
728 = $param =~ m/^-name$/i
730 : $param; # allow delete(-name=>'foo') syntax
731 return undef unless defined $self->{$param};
732 delete $self->{$param};
733 delete $self->{'.fieldnames'}->{$param};
734 $self->{'.parameters'}
735 = [ grep { $_ ne $param } @{ $self->{'.parameters'} } ];
738 sub Delete { CGI::Simple::delete( @_ ) } # for method style interface
743 $self->_store_globals;
746 sub Delete_all { $_[0]->delete_all } # as used by CGI.pm
749 my ( $self, $filename, $writefile ) = @_;
750 unless ( $filename ) {
751 $self->cgi_error( "No filename submitted for upload to $writefile" )
753 return $self->{'.filehandles'}
754 ? keys %{ $self->{'.filehandles'} }
757 unless ( $ENV{'CONTENT_TYPE'} =~ m|^multipart/form-data|i ) {
759 'Oops! File uploads only work if you specify ENCTYPE="multipart/form-data" in your <FORM> tag'
763 my $fh = $self->{'.filehandles'}->{$filename};
765 # allow use of upload fieldname to get filehandle
766 # this has limitation that in the event of duplicate
767 # upload field names there can only be one filehandle
768 # which will point to the last upload file
769 # access by filename does not suffer from this issue.
771 = $self->{'.filehandles'}->{ $self->{'.upload_fields'}->{$filename} }
772 if !$fh and defined $self->{'.upload_fields'}->{$filename};
775 seek $fh, 0, 0; # get ready for reading
776 return $fh unless $writefile;
778 unless ( open OUT, ">$writefile" ) {
779 $self->cgi_error( "500 Can't write to $writefile: $!\n" );
784 print OUT $buffer while read( $fh, $buffer, 4096 );
786 $self->{'.filehandles'}->{$filename} = undef;
792 "No filehandle for '$filename'. Are uploads enabled (\$DISABLE_UPLOADS = 0)? Is \$POST_MAX big enough?"
798 sub upload_fieldnames {
801 ? ( keys %{ $self->{'.upload_fields'} } )
802 : [ keys %{ $self->{'.upload_fields'} } ];
805 # return the file size of an uploaded file
807 my ( $self, $filename, $info ) = @_;
808 unless ( $ENV{'CONTENT_TYPE'} =~ m|^multipart/form-data|i ) {
810 'Oops! File uploads only work if you specify ENCTYPE="multipart/form-data" in your <FORM> tag'
814 return keys %{ $self->{'.tmpfiles'} } unless $filename;
815 return $self->{'.tmpfiles'}->{$filename}->{'mime'}
817 return $self->{'.tmpfiles'}->{$filename}->{'size'};
820 sub uploadInfo { &upload_info } # alias for CGI.pm compatibility
822 # return all params/values in object as a query string suitable for 'GET'
826 for my $param ( $self->param ) {
827 for my $value ( $self->param( $param ) ) {
828 next unless defined $value;
830 $self->url_encode( $param ) . '=' . $self->url_encode( $value );
833 return join $self->{'.globals'}->{'USE_PARAM_SEMICOLONS'} ? ';' : '&',
837 # new method that will add QUERY_STRING data to our CGI::Simple object
838 # if the REQUEST_METHOD was 'POST'
839 sub parse_query_string {
841 $self->_parse_params( $ENV{'QUERY_STRING'} )
842 if defined $ENV{'QUERY_STRING'}
843 and $ENV{'REQUEST_METHOD'} eq 'POST';
846 ################ Save and Restore params from file ###############
848 sub _init_from_file {
849 use Carp qw(confess);
850 confess "INIT_FROM_FILE called, stupid fucker!";
851 my ( $self, $fh ) = @_;
853 while ( my $pair = <$fh> ) {
855 return if $pair eq '=';
856 $self->_parse_params( $pair );
861 my ( $self, $fh ) = @_;
862 local ( $,, $\ ) = ( '', '' );
863 unless ( $fh and fileno $fh ) {
864 $self->cgi_error( 'Invalid filehandle' );
867 for my $param ( $self->param ) {
868 for my $value ( $self->param( $param ) ) {
870 print $fh $self->url_encode( $param ), '=',
871 $self->url_encode( $value ), "\n";
877 sub save_parameters { save( @_ ) } # CGI.pm alias for save
879 ################ Miscellaneous Methods ################
881 sub parse_keywordlist {
882 _parse_keywordlist( @_ );
883 } # CGI.pm compatibility
886 my ( $self, $escape, $newlinestoo ) = @_;
887 require CGI::Simple::Util;
888 $escape = CGI::Simple::Util::escapeHTML( $escape );
889 $escape =~ s/([\012\015])/'&#'.(ord $1).';'/eg if $newlinestoo;
894 require CGI::Simple::Util;
895 return CGI::Simple::Util::unescapeHTML( $_[1] );
901 } # send output to browser
906 } # print to standard output (for overriding in mod_perl)
908 ################# Cookie Methods ################
911 my ( $self, @params ) = @_;
912 require CGI::Simple::Cookie;
913 require CGI::Simple::Util;
914 my ( $name, $value, $path, $domain, $secure, $expires, $httponly )
915 = CGI::Simple::Util::rearrange(
917 'NAME', [ 'VALUE', 'VALUES' ],
925 # retrieve the value of the cookie, if no value is supplied
926 unless ( defined( $value ) ) {
927 $self->{'.cookies'} = CGI::Simple::Cookie->fetch
928 unless $self->{'.cookies'};
929 return () unless $self->{'.cookies'};
931 # if no name is supplied, then retrieve the names of all our cookies.
932 return keys %{ $self->{'.cookies'} } unless $name;
934 # return the value of the cookie
936 exists $self->{'.cookies'}->{$name}
937 ? $self->{'.cookies'}->{$name}->value
941 # If we get here, we're creating a new cookie
942 return undef unless $name; # this is an error
944 push @params, '-name' => $name;
945 push @params, '-value' => $value;
946 push @params, '-domain' => $domain if $domain;
947 push @params, '-path' => $path if $path;
948 push @params, '-expires' => $expires if $expires;
949 push @params, '-secure' => $secure if $secure;
950 push @params, '-httponly' => $httponly if $httponly;
951 return CGI::Simple::Cookie->new( @params );
955 my ( $self, $key ) = @_;
956 if ( defined $key ) {
957 unless ( $self->{'.raw_cookies'} ) {
958 require CGI::Simple::Cookie;
959 $self->{'.raw_cookies'} = CGI::Simple::Cookie->raw_fetch;
961 return $self->{'.raw_cookies'}->{$key} || ();
963 return $ENV{'HTTP_COOKIE'} || $ENV{'COOKIE'} || '';
966 ################# Header Methods ################
969 my ( $self, @params ) = @_;
970 require CGI::Simple::Util;
973 if $self->{'.header_printed'}++
974 and $self->{'.globals'}->{'HEADERS_ONCE'};
976 $type, $status, $cookie, $target, $expires,
977 $nph, $charset, $attachment, $p3p, @other
979 = CGI::Simple::Util::rearrange(
981 [ 'TYPE', 'CONTENT_TYPE', 'CONTENT-TYPE' ], 'STATUS',
982 [ 'COOKIE', 'COOKIES', 'SET-COOKIE' ], 'TARGET',
984 'CHARSET', 'ATTACHMENT',
989 $nph ||= $self->{'.globals'}->{'NPH'};
990 $charset = $self->charset( $charset )
991 ; # get charset (and set new charset if supplied)
992 # rearrange() was designed for the HTML portion, so we need to fix it up a little.
996 # Don't use \s because of perl bug 21951
998 unless my ( $header, $value ) = /([^ \r\n\t=]+)=\"?(.+?)\"?$/;
1000 =~ s/^(\w)(.*)/"\u$1\L$2" . ': '.$self->unescapeHTML($value)/e;
1002 $type ||= 'text/html' unless defined $type;
1003 $type .= "; charset=$charset"
1005 and $type =~ m!^text/!
1006 and $type !~ /\bcharset\b/;
1007 my $protocol = $ENV{SERVER_PROTOCOL} || 'HTTP/1.0';
1008 push @header, $protocol . ' ' . ( $status || '200 OK' ) if $nph;
1009 push @header, "Server: " . server_software() if $nph;
1010 push @header, "Status: $status" if $status;
1011 push @header, "Window-Target: $target" if $target;
1014 $p3p = join ' ', @$p3p if ref( $p3p ) eq 'ARRAY';
1015 push( @header, qq(P3P: policyref="/w3c/p3p.xml", CP="$p3p") );
1018 # push all the cookies -- there may be several
1020 my @cookie = ref $cookie eq 'ARRAY' ? @{$cookie} : $cookie;
1021 for my $cookie ( @cookie ) {
1023 = ref $cookie eq 'CGI::Simple::Cookie'
1024 ? $cookie->as_string
1026 push @header, "Set-Cookie: $cs" if $cs;
1030 # if the user indicates an expiration time, then we need both an Expires
1031 # and a Date header (so that the browser is using OUR clock)
1033 if $self->no_cache; # encourage no caching via expires now
1035 "Expires: " . CGI::Simple::Util::expires( $expires, 'http' )
1037 push @header, "Date: " . CGI::Simple::Util::expires( 0, 'http' )
1038 if defined $expires || $cookie || $nph;
1039 push @header, "Pragma: no-cache" if $self->cache or $self->no_cache;
1041 "Content-Disposition: attachment; filename=\"$attachment\""
1043 push @header, @other;
1044 push @header, "Content-Type: $type" if $type;
1045 my $CRLF = $self->crlf;
1046 my $header = join $CRLF, @header;
1047 $header .= $CRLF . $CRLF; # add the statutory two CRLFs
1049 if ( $self->{'.mod_perl'} and not $nph ) {
1050 my $r = $self->_mod_perl_request();
1051 $r->send_cgi_header( $header );
1057 # Control whether header() will produce the no-cache Pragma directive.
1059 my ( $self, $value ) = @_;
1060 $self->{'.cache'} = $value if defined $value;
1061 return $self->{'.cache'};
1064 # Control whether header() will produce expires now + the no-cache Pragma.
1066 my ( $self, $value ) = @_;
1067 $self->{'.no_cache'} = $value if defined $value;
1068 return $self->{'.no_cache'};
1072 my ( $self, @params ) = @_;
1073 require CGI::Simple::Util;
1074 my ( $url, $target, $cookie, $nph, @other )
1075 = CGI::Simple::Util::rearrange(
1077 [ 'LOCATION', 'URI', 'URL' ], 'TARGET',
1078 [ 'COOKIE', 'COOKIES' ], 'NPH'
1082 $url ||= $self->self_url;
1084 for ( @other ) { tr/\"//d; push @o, split "=", $_, 2; }
1086 '-Status' => '302 Moved',
1087 '-Location' => $url,
1089 unshift @o, '-Target' => $target if $target;
1090 unshift @o, '-Cookie' => $cookie if $cookie;
1091 unshift @o, '-Type' => '';
1093 unshift( @unescaped, '-Cookie' => $cookie ) if $cookie;
1094 return $self->header( ( map { $self->unescapeHTML( $_ ) } @o ),
1098 ################# Server Push Methods #################
1099 # Return a Content-Type: style header for server-push
1100 # This has to be NPH, and it is advisable to set $| = 1
1101 # Credit to Ed Jordan <ed@fidalgo.net> and
1102 # Andrew Benham <adsb@bigfoot.com> for this section
1104 sub multipart_init {
1105 my ( $self, @p ) = @_;
1106 use CGI::Simple::Util qw(rearrange);
1107 my ( $boundary, @other ) = rearrange( ['BOUNDARY'], @p );
1108 $boundary = $boundary || '------- =_aaaaaaaaaa0';
1109 my $CRLF = $self->crlf; # get CRLF sequence
1111 = "WARNING: YOUR BROWSER DOESN'T SUPPORT THIS SERVER-PUSH TECHNOLOGY.";
1112 $self->{'.separator'} = "$CRLF--$boundary$CRLF";
1113 $self->{'.final_separator'} = "$CRLF--$boundary--$CRLF$warning$CRLF";
1114 my $type = 'multipart/x-mixed-replace;boundary="' . $boundary . '"';
1115 return $self->header(
1118 map { split "=", $_, 2 } @other
1121 . $self->multipart_end;
1124 sub multipart_start {
1125 my ( $self, @p ) = @_;
1126 use CGI::Simple::Util qw(rearrange);
1127 my ( $type, @other ) = rearrange( ['TYPE'], @p );
1128 foreach ( @other ) { # fix return from rearange
1129 next unless my ( $header, $value ) = /([^\s=]+)=\"?(.+?)\"?$/;
1130 $_ = ucfirst( lc $header ) . ': ' . unescapeHTML( 1, $value );
1132 $type = $type || 'text/html';
1133 my @header = ( "Content-Type: $type" );
1134 push @header, @other;
1135 my $CRLF = $self->crlf; # get CRLF sequence
1136 return ( join $CRLF, @header ) . $CRLF . $CRLF;
1139 sub multipart_end { return $_[0]->{'.separator'} }
1141 sub multipart_final { return $_[0]->{'.final_separator'} }
1143 ################# Debugging Methods ################
1145 sub read_from_cmdline {
1147 if ( $_[0]->{'.globals'}->{'DEBUG'} == 1 and @ARGV ) {
1150 elsif ( $_[0]->{'.globals'}->{'DEBUG'} == 2 ) {
1151 require "shellwords.pl";
1152 print "(offline mode: enter name=value pairs on standard input)\n";
1153 chomp( my @lines = <STDIN> );
1154 @words = &shellwords( join " ", @lines );
1159 @words = map { s/\\=/%3D/g; s/\\&/%26/g; $_ } @words;
1160 return "@words" =~ m/=/ ? join '&', @words : join '+', @words;
1164 require Data::Dumper; # short and sweet way of doing it
1165 ( my $dump = Data::Dumper::Dumper( @_ ) )
1166 =~ tr/\000/0/; # remove null bytes cgi-lib.pl
1167 return '<pre>' . escapeHTML( 1, $dump ) . '</pre>';
1170 sub as_string { Dump( @_ ) } # CGI.pm alias for Dump()
1173 my ( $self, $err ) = @_;
1175 $self->{'.cgi_error'} = $err;
1176 $self->{'.globals'}->{'FATAL'} == 1 ? croak $err
1177 : $self->{'.globals'}->{'FATAL'} == 0 ? carp $err
1180 return $self->{'.cgi_error'};
1183 ################# cgi-lib.pl Compatibility Methods #################
1184 # Lightly GOLFED but the original functionality remains. You can call
1185 # them using either: # $q->MethodName or CGI::Simple::MethodName
1187 sub _shift_if_ref { shift if ref $_[0] eq 'CGI::Simple' }
1190 my $q = &_shift_if_ref || new CGI::Simple;
1196 : *{"${pkg}::in"}; # set *in to passed glob or export *in
1205 && ( wantarray ? split "\0", $_[0] : ( split "\0", $_[0] )[0] );
1208 sub MethGet { request_method() eq 'GET' }
1210 sub MethPost { request_method() eq 'POST' }
1216 . ( server_port() != 80 ? ':' . server_port() : '' )
1220 sub MyURL { MyBaseUrl() }
1226 . ( $ENV{'QUERY_STRING'} ? "?$ENV{'QUERY_STRING'}" : '' );
1230 ref $_[0] ? $_[0]->header() : "Content-Type: text/html\n\n";
1235 "<html>\n<head>\n<title>$_[0]</title>\n</head>\n<body>\n<h1>$_[0]</h1>\n";
1238 sub HtmlBot { "</body>\n</html>\n" }
1240 sub PrintVariables { &_shift_if_ref; &Dump }
1242 sub PrintEnv { &Dump( \%ENV ) }
1244 sub CgiDie { CgiError( @_ ); die @_ }
1251 : ( "Error: script " . MyFullUrl() . " encountered fatal error\n" );
1252 print PrintHeader(), HtmlTop( shift ), ( map { "<p>$_</p>\n" } @_ ),
1256 ################ Accessor Methods ################
1258 sub version { $VERSION }
1261 $_[0]->{'.globals'}->{'NPH'} = $_[1] if defined $_[1];
1262 return $_[0]->{'.globals'}->{'NPH'};
1265 sub all_parameters { $_[0]->param }
1268 require CGI::Simple::Util;
1269 $CGI::Simple::Util::UTIL->charset( $_[1] );
1273 my ( $self, $global, $value ) = @_;
1274 return keys %{ $self->{'.globals'} } unless $global;
1275 $self->{'.globals'}->{$global} = $value if defined $value;
1276 return $self->{'.globals'}->{$global};
1279 sub auth_type { $ENV{'AUTH_TYPE'} }
1280 sub content_length { $ENV{'CONTENT_LENGTH'} }
1281 sub content_type { $ENV{'CONTENT_TYPE'} }
1282 sub document_root { $ENV{'DOCUMENT_ROOT'} }
1283 sub gateway_interface { $ENV{'GATEWAY_INTERFACE'} }
1284 sub path_translated { $ENV{'PATH_TRANSLATED'} }
1285 sub referer { $ENV{'HTTP_REFERER'} }
1286 sub remote_addr { $ENV{'REMOTE_ADDR'} || '127.0.0.1' }
1289 $ENV{'REMOTE_HOST'} || $ENV{'REMOTE_ADDR'} || 'localhost';
1292 sub remote_ident { $ENV{'REMOTE_IDENT'} }
1293 sub remote_user { $ENV{'REMOTE_USER'} }
1294 sub request_method { $ENV{'REQUEST_METHOD'} }
1295 sub script_name { $ENV{'SCRIPT_NAME'} || $0 || '' }
1296 sub server_name { $ENV{'SERVER_NAME'} || 'localhost' }
1297 sub server_port { $ENV{'SERVER_PORT'} || 80 }
1298 sub server_protocol { $ENV{'SERVER_PROTOCOL'} || 'HTTP/1.0' }
1299 sub server_software { $ENV{'SERVER_SOFTWARE'} || 'cmdline' }
1302 $ENV{'HTTP_FROM'} || $ENV{'REMOTE_IDENT'} || $ENV{'REMOTE_USER'};
1306 my ( $self, $match ) = @_;
1308 ? $ENV{'HTTP_USER_AGENT'} =~ /\Q$match\E/i
1309 : $ENV{'HTTP_USER_AGENT'};
1313 my $vh = $ENV{'HTTP_HOST'} || $ENV{'SERVER_NAME'};
1314 $vh =~ s/:\d+$//; # get rid of port number
1319 my ( $self, $info ) = @_;
1320 if ( defined $info ) {
1321 $info = "/$info" if $info !~ m|^/|;
1322 $self->{'.path_info'} = $info;
1324 elsif ( !defined( $self->{'.path_info'} ) ) {
1325 $self->{'.path_info'}
1326 = defined( $ENV{'PATH_INFO'} ) ? $ENV{'PATH_INFO'} : '';
1328 # hack to fix broken path info in IIS source CGI.pm
1329 $self->{'.path_info'} =~ s/^\Q$ENV{'SCRIPT_NAME'}\E//
1330 if defined( $ENV{'SERVER_SOFTWARE'} )
1331 && $ENV{'SERVER_SOFTWARE'} =~ /IIS/;
1333 return $self->{'.path_info'};
1337 my ( $self, $search ) = @_;
1339 for my $accept ( split ',', $ENV{'HTTP_ACCEPT'} ) {
1340 ( my $pref ) = $accept =~ m|q=([\d\.]+)|;
1341 ( my $type ) = $accept =~ m|(\S+/[^;]+)|;
1343 $prefs{$type} = $pref || 1;
1345 return keys %prefs unless $search;
1346 return $prefs{$search} if $prefs{$search};
1348 # Didn't get it, so try pattern matching.
1349 for my $pref ( keys %prefs ) {
1350 next unless $pref =~ m/\*/; # not a pattern match
1351 ( my $pat = $pref ) =~ s/([^\w*])/\\$1/g; # escape meta characters
1352 $pat =~ s/\*/.*/g; # turn it into a pattern
1353 return $prefs{$pref} if $search =~ /$pat/;
1357 sub Accept { my $self = shift; $self->accept( @_ ) }
1360 my ( $self, $parameter ) = @_;
1361 if ( defined $parameter ) {
1362 ( $parameter = uc $parameter ) =~ tr/-/_/;
1363 return $ENV{$parameter} if $parameter =~ m/^HTTP/;
1364 return $ENV{"HTTP_$parameter"} if $parameter;
1366 return grep { /^HTTP/ } keys %ENV;
1370 my ( $self, $parameter ) = @_;
1371 return $ENV{'HTTPS'} unless $parameter;
1372 ( $parameter = uc $parameter ) =~ tr/-/_/;
1373 return $ENV{$parameter} if $parameter =~ /^HTTPS/;
1374 return $ENV{"HTTPS_$parameter"};
1380 return 'https' if uc $ENV{'HTTPS'} eq 'ON';
1381 return 'https' if $self->server_port == 443;
1382 my ( $protocol, $version ) = split '/', $self->server_protocol;
1383 return lc $protocol;
1387 my ( $self, @p ) = @_;
1388 use CGI::Simple::Util 'rearrange';
1389 my ( $relative, $absolute, $full, $path_info, $query, $base )
1392 'RELATIVE', 'ABSOLUTE', 'FULL',
1393 [ 'PATH', 'PATH_INFO' ],
1394 [ 'QUERY', 'QUERY_STRING' ], 'BASE'
1399 $full++ if $base || !( $relative || $absolute );
1400 my $path = $self->path_info;
1401 my $script_name = $self->script_name;
1403 my $protocol = $self->protocol();
1404 $url = "$protocol://";
1405 my $vh = $self->http( 'host' );
1410 $url .= server_name();
1411 my $port = $self->server_port;
1413 unless ( lc( $protocol ) eq 'http' && $port == 80 )
1414 or ( lc( $protocol ) eq 'https' && $port == 443 );
1416 return $url if $base;
1417 $url .= $script_name;
1419 elsif ( $relative ) {
1420 ( $url ) = $script_name =~ m#([^/]+)$#;
1422 elsif ( $absolute ) {
1423 $url = $script_name;
1425 $url .= $path if $path_info and defined $path;
1426 $url .= "?" . $self->query_string if $query and $self->query_string;
1427 $url = '' unless defined $url;
1429 =~ s/([^a-zA-Z0-9_.%;&?\/\\:+=~-])/uc sprintf("%%%02x",ord($1))/eg;
1434 my ( $self, @params ) = @_;
1443 sub state { self_url( @_ ) } # CGI.pm synonym routine
1449 CGI::Simple - A Simple totally OO CGI interface that is CGI.pm compliant
1453 This document describes CGI::Simple version 1.112.
1458 $CGI::Simple::POST_MAX = 1024; # max upload via post default 100kB
1459 $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads
1461 $q = new CGI::Simple;
1462 $q = new CGI::Simple( { 'foo'=>'1', 'bar'=>[2,3,4] } );
1463 $q = new CGI::Simple( 'foo=1&bar=2&bar=3&bar=4' );
1464 $q = new CGI::Simple( \*FILEHANDLE );
1466 $q->save( \*FILEHANDLE ); # save current object to a file as used by new
1468 @params = $q->param; # return all param names as a list
1469 $value = $q->param('foo'); # return the first value supplied for 'foo'
1470 @values = $q->param('foo'); # return all values supplied for foo
1472 %fields = $q->Vars; # returns untied key value pair hash
1473 $hash_ref = $q->Vars; # or as a hash ref
1474 %fields = $q->Vars("|"); # packs multiple values with "|" rather than "\0";
1476 @keywords = $q->keywords; # return all keywords as a list
1478 $q->param( 'foo', 'some', 'new', 'values' ); # set new 'foo' values
1479 $q->param( -name=>'foo', -value=>'bar' );
1480 $q->param( -name=>'foo', -value=>['bar','baz'] );
1482 $q->param( 'foo', 'some', 'new', 'values' ); # append values to 'foo'
1483 $q->append( -name=>'foo', -value=>'bar' );
1484 $q->append( -name=>'foo', -value=>['some', 'new', 'values'] );
1486 $q->delete('foo'); # delete param 'foo' and all its values
1487 $q->delete_all; # delete everything
1489 <INPUT TYPE="file" NAME="upload_file" SIZE="42">
1491 $files = $q->upload() # number of files uploaded
1492 @files = $q->upload(); # names of all uploaded files
1493 $filename = $q->param('upload_file') # filename of uploaded file
1494 $mime = $q->upload_info($filename,'mime'); # MIME type of uploaded file
1495 $size = $q->upload_info($filename,'size'); # size of uploaded file
1497 my $fh = $q->upload($filename); # get filehandle to read from
1498 while ( read( $fh, $buffer, 1024 ) ) { ... }
1500 # short and sweet upload
1501 $ok = $q->upload( $q->param('upload_file'), '/path/to/write/file.name' );
1502 print "Uploaded ".$q->param('upload_file')." and wrote it OK!" if $ok;
1504 $decoded = $q->url_decode($encoded);
1505 $encoded = $q->url_encode($unencoded);
1506 $escaped = $q->escapeHTML('<>"&');
1507 $unescaped = $q->unescapeHTML('<>"&');
1509 $qs = $q->query_string; # get all data in $q as a query string OK for GET
1511 $q->no_cache(1); # set Pragma: no-cache + expires
1512 print $q->header(); # print a simple header
1513 # get a complex header
1514 $header = $q->header( -type => 'image/gif'
1516 -status => '402 Payment required',
1519 -charset => 'utf-7',
1520 -attachment => 'foo.gif',
1523 # a p3p header (OK for redirect use as well)
1524 $header = $q->header( -p3p => 'policyref="http://somesite.com/P3P/PolicyReferences.xml' );
1526 @cookies = $q->cookie(); # get names of all available cookies
1527 $value = $q->cookie('foo') # get first value of cookie 'foo'
1528 @value = $q->cookie('foo') # get all values of cookie 'foo'
1529 # get a cookie formatted for header() method
1530 $cookie = $q->cookie( -name => 'Password',
1531 -values => ['superuser','god','my dog woofie'],
1533 -domain => '.nowhere.com',
1534 -path => '/cgi-bin/database',
1537 print $q->header( -cookie=>$cookie ); # set cookie
1539 print $q->redirect('http://go.away.now'); # print a redirect header
1541 dienice( $q->cgi_error ) if $q->cgi_error;
1545 CGI::Simple provides a relatively lightweight drop in replacement for CGI.pm.
1546 It shares an identical OO interface to CGI.pm for parameter parsing, file
1547 upload, cookie handling and header generation. This module is entirely object
1548 oriented, however a complete functional interface is available by using the
1549 CGI::Simple::Standard module.
1551 Essentially everything in CGI.pm that relates to the CGI (not HTML) side of
1552 things is available. There are even a few new methods and additions to old
1553 ones! If you are interested in what has gone on under the hood see the
1554 Compatibility with CGI.pm section at the end.
1556 In practical testing this module loads and runs about twice as fast as CGI.pm
1557 depending on the precise task.
1559 =head1 CALLING CGI::Simple ROUTINES USING THE OBJECT INTERFACE
1561 Here is a very brief rundown on how you use the interface. Full details
1564 =head2 First you need to initialize an object
1566 Before you can call a CGI::Simple method you must create a CGI::Simple object.
1567 You do that by using the module and then calling the new() constructor:
1570 my $q = new CGI::Simple;
1572 It is traditional to call your object $q for query or perhaps $cgi.
1574 =head2 Next you call methods on that object
1576 Once you have your object you can call methods on it using the -> arrow
1577 syntax For example to get the names of all the parameters passed to your
1578 script you would just write:
1580 @names = $q->param();
1582 Many methods are sensitive to the context in which you call them. In the
1583 example above the B<param()> method returns a list of all the parameter names
1584 when called without any arguments.
1586 When you call B<param('arg')> with a single argument it assumes you want
1587 to get the value(s) associated with that argument (parameter). If you ask
1588 for an array it gives you an array of all the values associated with it's
1591 @values = $q->param('foo'); # get all the values for 'foo'
1593 whereas if you ask for a scalar like this:
1595 $value = $q->param('foo'); # get only the first value for 'foo'
1597 then it returns only the first value (if more than one value for
1600 Most CGI::Simple routines accept several arguments, sometimes as many as
1601 10 optional ones! To simplify this interface, all routines use a named
1602 argument calling style that looks like this:
1604 print $q->header( -type=>'image/gif', -expires=>'+3d' );
1606 Each argument name is preceded by a dash. Neither case nor order
1607 matters in the argument list. -type, -Type, and -TYPE are all
1610 Several routines are commonly called with just one argument. In the
1611 case of these routines you can provide the single argument without an
1612 argument name. B<header()> happens to be one of these routines. In this
1613 case, the single argument is the document type.
1615 print $q->header('text/html');
1617 Sometimes methods expect a scalar, sometimes a reference to an
1618 array, and sometimes a reference to a hash. Often, you can pass any
1619 type of argument and the routine will do whatever is most appropriate.
1620 For example, the B<param()> method can be used to set a CGI parameter to a
1621 single or a multi-valued value. The two cases are shown below:
1623 $q->param(-name=>'veggie',-value=>'tomato');
1624 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
1626 =head1 CALLING CGI::Simple ROUTINES USING THE FUNCTION INTERFACE
1628 For convenience a functional interface is provided by the
1629 CGI::Simple::Standard module. This hides the OO details from you and allows
1630 you to simply call methods. You may either use AUTOLOADING of methods or
1631 import specific method sets into you namespace. Here are the first few
1632 examples again using the function interface.
1634 use CGI::Simple::Standard qw(-autoload);
1636 @values = param('foo');
1637 $value = param('foo');
1638 print header(-type=>'image/gif',-expires=>'+3d');
1639 print header('text/html');
1641 Yes that's it. Not a $q-> in sight. You just use the module and select
1642 how/which methods to load. You then just call the methods you want exactly
1643 as before but without the $q-> notation.
1645 When (if) you read the following docs and are using the functional interface
1646 just pretend the $q-> is not there.
1648 =head2 Selecting which methods to load
1650 When you use the functional interface Perl needs to be able to find the
1651 functions you call. The simplest way of doing this is to use autoloading as
1652 shown above. When you use CGI::Simple::Standard with the '-autoload' pragma
1653 it exports a single AUTOLOAD sub into you namespace. Every time you call a
1654 non existent function AUTOLOAD is called and will load the required
1655 function and install it in your namespace. Thus only the AUTOLOAD sub and
1656 those functions you specifically call will be imported.
1658 Alternatively CGI::Simple::Standard provides a range of function sets you can
1659 import or you can just select exactly what you want. You do this using the
1662 use CGI::Simple::Standard qw( :func_set some_func);
1664 notation. This will import the ':func_set' function set and the specific
1665 function 'some_func'.
1667 =head2 To Autoload or not to Autoload, that is the question.
1669 If you do not have a AUTOLOAD sub in you script it is generally best to use
1670 the '-autoload' option. Under autoload you can use any method you want but
1671 only import and compile those functions you actually use.
1673 If you do not use autoload you must specify what functions to import. You can
1674 only use functions that you have imported. For comvenience functions are
1675 grouped into related sets. If you choose to import one or more ':func_set'
1676 you may have potential namespace collisions so check out the docs to see
1677 what gets imported. Using the ':all' tag is pretty slack but it is there
1678 if you want. Full details of the function sets are provided in the
1679 CGI::Simple::Standard docs
1681 If you just want say the param and header methods just load these two.
1683 use CGI::Simple::Standard qw(param header);
1685 =head2 Setting globals using the functional interface
1687 Where you see global variables being set using the syntax:
1689 $CGI::Simple::DEBUG = 1;
1691 You use exactly the same syntax when using CGI::Simple::Standard.
1695 ################ The Core Methods ################
1697 =head1 THE CORE METHODS
1699 =head2 new() Creating a new query object
1701 The first step in using CGI::Simple is to create a new query object using
1702 the B<new()> constructor:
1704 $q = new CGI::Simple;
1706 This will parse the input (from both POST and GET methods) and store
1707 it into an object called $q.
1709 If you provide a file handle to the B<new()> method, it will read
1710 parameters from the file (or STDIN, or whatever).
1712 open FH, "test.in" or die $!;
1713 $q = new CGI::Simple(\*FH);
1715 open $fh, "test.in" or die $!;
1716 $q = new CGI::Simple($fh);
1718 The file should be a series of newline delimited TAG=VALUE pairs.
1719 Conveniently, this type of file is created by the B<save()> method
1720 (see below). Multiple records can be saved and restored.
1721 IO::File objects work fine.
1723 If you are using the function-oriented interface provided by
1724 CGI::Simple::Standard and want to initialize from a file handle,
1725 the way to do this is with B<restore_parameters()>. This will (re)initialize
1726 the default CGI::Simple object from the indicated file handle.
1728 restore_parameters(\*FH);
1730 In fact for all intents and purposes B<restore_parameters()> is identical
1731 to B<new()> Note that B<restore_parameters()> does not exist in
1732 CGI::Simple itself so you can't use it.
1734 You can also initialize the query object from an associative array
1737 $q = new CGI::Simple( { 'dinosaur' => 'barney',
1738 'song' => 'I love you',
1739 'friends' => [qw/Jessica George Nancy/] }
1742 or from a properly formatted, URL-escaped query string:
1744 $q = new CGI::Simple( 'dinosaur=barney&color=purple' );
1746 or from a previously existing CGI::Simple object (this generates an identical clone
1747 including all global variable settings, etc that are stored in the object):
1749 $old_query = new CGI::Simple;
1750 $new_query = new CGI::Simple($old_query);
1752 To create an empty query, initialize it from an empty string or hash:
1754 $empty_query = new CGI::Simple("");
1758 $empty_query = new CGI::Simple({});
1760 =head2 keywords() Fetching a list of keywords from a query
1762 @keywords = $q->keywords;
1764 If the script was invoked as the result of an <ISINDEX> search, the
1765 parsed keywords can be obtained as an array using the B<keywords()> method.
1767 =head2 param() Fetching the names of all parameters passed to your script
1771 If the script was invoked with a parameter list
1772 (e.g. "name1=value1&name2=value2&name3=value3"), the B<param()> method
1773 will return the parameter names as a list. If the script was invoked
1774 as an <ISINDEX> script and contains a string without ampersands
1775 (e.g. "value1+value2+value3") , there will be a single parameter named
1776 "keywords" containing the "+"-delimited keywords.
1778 NOTE: The array of parameter names returned will
1779 be in the same order as they were submitted by the browser.
1780 Usually this order is the same as the order in which the
1781 parameters are defined in the form (however, this isn't part
1782 of the spec, and so isn't guaranteed).
1784 =head2 param() Fetching the value or values of a simple named parameter
1786 @values = $q->param('foo');
1790 $value = $q->param('foo');
1792 Pass the B<param()> method a single argument to fetch the value of the
1793 named parameter. If the parameter is multi-valued (e.g. from multiple
1794 selections in a scrolling list), you can ask to receive an array. Otherwise
1795 the method will return a single value.
1797 If a value is not given in the query string, as in the queries
1798 "name1=&name2=" or "name1&name2", it will be returned by default
1799 as an empty string. If you set the global variable:
1801 $CGI::Simple::NO_UNDEF_PARAMS = 1;
1803 Then value-less parameters will be ignored, and will not exist in the
1804 query object. If you try to access them via param you will get an undef
1807 =head2 param() Setting the values of a named parameter
1809 $q->param('foo','an','array','of','values');
1811 This sets the value for the named parameter 'foo' to an array of
1812 values. This is one way to change the value of a field.
1814 B<param()> also recognizes a named parameter style of calling described
1815 in more detail later:
1817 $q->param(-name=>'foo',-values=>['an','array','of','values']);
1821 $q->param(-name=>'foo',-value=>'the value');
1823 =head2 param() Retrieving non-application/x-www-form-urlencoded data
1825 If POSTed or PUTed data is not of type application/x-www-form-urlencoded or multipart/form-data,
1826 then the data will not be processed, but instead be returned as-is in a parameter named POSTDATA
1827 or PUTDATA. To retrieve it, use code like this:
1829 my $data = $q->param( 'POSTDATA' );
1833 my $data = $q->param( 'PUTDATA' );
1835 (If you don't know what the preceding means, don't worry about it. It only affects people trying
1836 to use CGI::Simple for REST webservices)
1838 =head2 add_param() Setting the values of a named parameter
1840 You nay also use the new method B<add_param> to add parameters. This is an
1841 alias to the _add_param() internal method that actually does all the work.
1842 You can call it like this:
1844 $q->add_param('foo', 'new');
1845 $q->add_param('foo', [1,2,3,4,5]);
1846 $q->add_param( 'foo', 'bar', 'overwrite' );
1848 The first argument is the parameter, the second the value or an array ref
1849 of values and the optional third argument sets overwrite mode. If the third
1850 argument is absent of false the values will be appended. If true the values
1851 will overwrite any existing ones
1853 =head2 append() Appending values to a named parameter
1855 $q->append(-name=>'foo',-values=>['yet','more','values']);
1857 This adds a value or list of values to the named parameter. The
1858 values are appended to the end of the parameter if it already exists.
1859 Otherwise the parameter is created. Note that this method only
1860 recognizes the named argument calling syntax.
1862 =head2 import_names() Importing all parameters into a namespace.
1864 This method was silly, non OO and has been deleted. You can get all the params
1865 as a hash using B<Vars> or via all the other accessors.
1867 =head2 delete() Deleting a parameter completely
1871 This completely clears a parameter. If you are using the function call
1872 interface, use B<Delete()> instead to avoid conflicts with Perl's
1873 built-in delete operator.
1875 If you are using the function call interface, use B<Delete()> instead to
1876 avoid conflicts with Perl's built-in delete operator.
1878 =head2 delete_all() Deleting all parameters
1882 This clears the CGI::Simple object completely. For CGI.pm compatibility
1883 B<Delete_all()> is provided however there is no reason to use this in the
1884 function call interface other than symmetry.
1886 For CGI.pm compatibility B<Delete_all()> is provided as an alias for
1887 B<delete_all> however there is no reason to use this, even in the
1888 function call interface.
1890 =head2 param_fetch() Direct access to the parameter list
1892 This method is provided for CGI.pm compatibility only. It returns an
1893 array ref to the values associated with a named param. It is deprecated.
1895 =head2 Vars() Fetching the entire parameter list as a hash
1897 $params = $q->Vars; # as a tied hash ref
1898 print $params->{'address'};
1899 @foo = split "\0", $params->{'foo'};
1901 %params = $q->Vars; # as a plain hash
1902 print $params{'address'};
1903 @foo = split "\0", $params{'foo'};
1905 %params = $q->Vars(','); # specifying a different separator than "\0"
1906 @foo = split ',', $params{'foo'};
1908 Many people want to fetch the entire parameter list as a hash in which
1909 the keys are the names of the CGI parameters, and the values are the
1910 parameters' values. The B<Vars()> method does this.
1912 Called in a scalar context, it returns the parameter list as a tied
1913 hash reference. Because this hash ref is tied changing a key/value
1914 changes the underlying CGI::Simple object.
1916 Called in a list context, it returns the parameter list as an ordinary hash.
1917 Changing this hash will not change the underlying CGI::Simple object
1919 When using B<Vars()>, the thing you must watch out for are multi-valued CGI
1920 parameters. Because a hash cannot distinguish between scalar and
1921 list context, multi-valued parameters will be returned as a packed
1922 string, separated by the "\0" (null) character. You must split this
1923 packed string in order to get at the individual values. This is the
1924 convention introduced long ago by Steve Brenner in his cgi-lib.pl
1925 module for Perl version 4.
1927 You can change the character used to do the multiple value packing by passing
1928 it to B<Vars()> as an argument as shown.
1930 =head2 url_param() Access the QUERY_STRING regardless of 'GET' or 'POST'
1932 The B<url_param()> method makes the QUERY_STRING data available regardless
1933 of whether the REQUEST_METHOD was 'GET' or 'POST'. You can do anything
1934 with B<url_param> that you can do with B<param()>, however the data set
1935 is completely independent.
1937 Technically what happens if you use this method is that the QUERY_STRING data
1938 is parsed into a new CGI::Simple object which is stored within the current
1939 object. B<url_param> then just calls B<param()> on this new object.
1941 =head2 parse_query_string() Add QUERY_STRING data to 'POST' requests
1943 When the REQUEST_METHOD is 'POST' the default behavior is to ignore
1944 name/value pairs or keywords in the $ENV{'QUERY_STRING'}. You can override
1945 this by calling B<parse_query_string()> which will add the QUERY_STRING data to
1946 the data already in our CGI::Simple object if the REQUEST_METHOD was 'POST'
1948 $q = new CGI::Simple;
1949 $q->parse_query_string; # add $ENV{'QUERY_STRING'} data to our $q object
1951 If the REQUEST_METHOD was 'GET' then the QUERY_STRING will already be
1952 stored in our object so B<parse_query_string> will be ignored.
1954 This is a new method in CGI::Simple that is not available in CGI.pm
1956 =head2 save() Saving the state of an object to file
1958 $q->save(\*FILEHANDLE)
1960 This will write the current state of the form to the provided
1961 filehandle. You can read it back in by providing a filehandle
1962 to the B<new()> method.
1964 The format of the saved file is:
1972 Both name and value are URL escaped. Multi-valued CGI parameters are
1973 represented as repeated names. A session record is delimited by a
1974 single = symbol. You can write out multiple records and read them
1975 back in with several calls to B<new()>.
1977 open FH, "test.in" or die $!;
1978 $q1 = new CGI::Simple(\*FH); # get the first record
1979 $q2 = new CGI::Simple(\*FH); # get the next record
1981 Note: If you wish to use this method from the function-oriented (non-OO)
1982 interface, the exported name for this method is B<save_parameters()>.
1983 Also if you want to initialize from a file handle, the way to do this is
1984 with B<restore_parameters()>. This will (re)initialize
1985 the default CGI::Simple object from the indicated file handle.
1987 restore_parameters(\*FH);
1991 ################ Uploading Files ###################
1995 File uploads are easy with CGI::Simple. You use the B<upload()> method.
1996 Assuming you have the following in your HTML:
2000 ACTION="http://somewhere.com/cgi-bin/script.cgi"
2001 ENCTYPE="multipart/form-data">
2002 <INPUT TYPE="file" NAME="upload_file1" SIZE="42">
2003 <INPUT TYPE="file" NAME="upload_file2" SIZE="42">
2006 Note that the ENCTYPE is "multipart/form-data". You must specify this or the
2007 browser will default to "application/x-www-form-urlencoded" which will result
2008 in no files being uploaded although on the surface things will appear OK.
2010 When the user submits this form any supplied files will be spooled onto disk
2011 and saved in temporary files. These files will be deleted when your script.cgi
2012 exits so if you want to keep them you will need to proceed as follows.
2014 =head2 upload() The key file upload method
2016 The B<upload()> method is quite versatile. If you call B<upload()> without
2017 any arguments it will return a list of uploaded files in list context and
2018 the number of uploaded files in scalar context.
2020 $number_of_files = $q->upload;
2021 @list_of_files = $q->upload;
2023 Having established that you have uploaded files available you can get the
2024 browser supplied filename using B<param()> like this:
2026 $filename1 = $q->param('upload_file1');
2028 You can then get a filehandle to read from by calling B<upload()> and
2029 supplying this filename as an argument. Warning: do not modify the
2030 value you get from B<param()> in any way - you don't need to untaint it.
2032 $fh = $q->upload( $filename1 );
2034 Now to save the file you would just do something like:
2036 $save_path = '/path/to/write/file.name';
2037 open FH, ">$save_path" or die "Oops $!\n";
2039 print FH $buffer while read( $fh, $buffer, 4096 );
2042 By utilizing a new feature of the upload method this process can be
2045 $ok = $q->upload( $q->param('upload_file1'), '/path/to/write/file.name' );
2047 print "Uploaded and wrote file OK!";
2049 print $q->cgi_error();
2052 As you can see upload will accept an optional second argument and will write
2053 the file to this file path. It will return 1 for success and undef if it
2054 fails. If it fails you can get the error from B<cgi_error>
2056 You can also use just the fieldname as an argument to upload ie:
2058 $fh = $q->upload( 'upload_field_name' );
2062 $ok = $q->upload( 'upload_field_name', '/path/to/write/file.name' );
2064 BUT there is a catch. If you have multiple upload fields, all called
2065 'upload_field_name' then you will only get the last uploaded file from
2068 =head2 upload_info() Get the details about uploaded files
2070 The B<upload_info()> method is a new method. Called without arguments it
2071 returns the number of uploaded files in scalar context and the names of
2072 those files in list context.
2074 $number_of_upload_files = $q->upload_info();
2075 @filenames_of_all_uploads = $q->upload_info();
2077 You can get the MIME type of an uploaded file like this:
2079 $mime = $q->upload_info( $filename1, 'mime' );
2081 If you want to know how big a file is before you copy it you can get that
2082 information from B<uploadInfo> which will return the file size in bytes.
2084 $file_size = $q->upload_info( $filename1, 'size' );
2086 The size attribute is optional as this is the default value returned.
2088 Note: The old CGI.pm B<uploadInfo()> method has been deleted.
2090 =head2 $POST_MAX and $DISABLE_UPLOADS
2092 CGI.pm has a default setting that allows infinite size file uploads by
2093 default. In contrast file uploads are disabled by default in CGI::Simple
2094 to discourage Denial of Service attacks. You must enable them before you
2095 expect file uploads to work.
2097 When file uploads are disabled the file name and file size details will
2098 still be available from B<param()> and B<upload_info> respectively but
2099 the upload filehandle returned by B<upload()> will be undefined - not
2100 surprising as the underlying temp file will not exist either.
2102 You can enable uploads using the '-upload' pragma. You do this by specifying
2103 this in you use statement:
2105 use CGI::Simple qw(-upload);
2107 Alternatively you can enable uploads via the $DISABLE_UPLOADS global like this:
2110 $CGI::Simple::DISABLE_UPLOADS = 0;
2111 $q = new CGI::Simple;
2113 If you wish to set $DISABLE_UPLOADS you must do this *after* the
2114 use statement and *before* the new constructor call as shown above.
2116 The maximum acceptable data via post is capped at 102_400kB rather than
2117 infinity which is the CGI.pm default. This should be ample for most tasks
2118 but you can set this to whatever you want using the $POST_MAX global.
2121 $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads
2122 $CGI::Simple::POST_MAX = 1_048_576; # allow 1MB uploads
2123 $q = new CGI::Simple;
2125 If you set to -1 infinite size uploads will be permitted, which is the CGI.pm
2128 $CGI::Simple::POST_MAX = -1; # infinite size upload
2130 Alternatively you can specify all the CGI.pm default values which allow file
2131 uploads of infinite size in one easy step by specifying the '-default' pragma
2132 in your use statement.
2134 use CGI::Simple qw( -default ..... );
2136 =head2 binmode() and Win32
2138 If you are using CGI::Simple be sure to call B<binmode()> on any handle that
2139 you create to write the uploaded file to disk. Calling B<binmode()> will do
2140 no harm on other systems anyway.
2144 ################ Miscellaneous Methods ################
2146 =head1 MISCELANEOUS METHODS
2148 =head2 escapeHTML() Escaping HTML special characters
2150 In HTML the < > " and & chars have special meaning and need to be
2151 escaped to < > " and & respectively.
2153 $escaped = $q->escapeHTML( $string );
2155 $escaped = $q->escapeHTML( $string, 'new_lines_too' );
2157 If the optional second argument is supplied then newlines will be escaped to.
2159 =head2 unescapeHTML() Unescape HTML special characters
2161 This performs the reverse of B<escapeHTML()>.
2163 $unescaped = $q->unescapeHTML( $HTML_escaped_string );
2165 =head2 url_decode() Decode a URL encoded string
2167 This method will correctly decode a url encoded string.
2169 $decoded = $q->url_decode( $encoded );
2171 =head2 url_encode() URL encode a string
2173 This method will correctly URL encode a string.
2175 $encoded = $q->url_encode( $string );
2177 =head2 parse_keywordlist() Parse a supplied keyword list
2179 @keywords = $q->parse_keywordlist( $keyword_list );
2181 This method returns a list of keywords, correctly URL escaped and split out
2182 of the supplied string
2184 =head2 put() Send output to browser
2186 CGI.pm alias for print. $q->put('Hello World!') will print the usual
2188 =head2 print() Send output to browser
2190 CGI.pm alias for print. $q->print('Hello World!') will print the usual
2194 ################# Cookie Methods ################
2198 CGI.pm has several methods that support cookies.
2200 A cookie is a name=value pair much like the named parameters in a CGI
2201 query string. CGI scripts create one or more cookies and send
2202 them to the browser in the HTTP header. The browser maintains a list
2203 of cookies that belong to a particular Web server, and returns them
2204 to the CGI script during subsequent interactions.
2206 In addition to the required name=value pair, each cookie has several
2207 optional attributes:
2211 =item 1. an expiration time
2213 This is a time/date string (in a special GMT format) that indicates
2214 when a cookie expires. The cookie will be saved and returned to your
2215 script until this expiration date is reached if the user exits
2216 the browser and restarts it. If an expiration date isn't specified, the cookie
2217 will remain active until the user quits the browser.
2221 This is a partial or complete domain name for which the cookie is
2222 valid. The browser will return the cookie to any host that matches
2223 the partial domain name. For example, if you specify a domain name
2224 of ".capricorn.com", then the browser will return the cookie to
2225 Web servers running on any of the machines "www.capricorn.com",
2226 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
2227 must contain at least two periods to prevent attempts to match
2228 on top level domains like ".edu". If no domain is specified, then
2229 the browser will only return the cookie to servers on the host the
2230 cookie originated from.
2234 If you provide a cookie path attribute, the browser will check it
2235 against your script's URL before returning the cookie. For example,
2236 if you specify the path "/cgi-bin", then the cookie will be returned
2237 to each of the scripts "/cgi-bin/tally.pl", "/cgi-bin/order.pl",
2238 and "/cgi-bin/customer_service/complain.pl", but not to the script
2239 "/cgi-private/site_admin.pl". By default, path is set to "/", which
2240 causes the cookie to be sent to any CGI script on your site.
2242 =item 4. a "secure" flag
2244 If the "secure" attribute is set, the cookie will only be sent to your
2245 script if the CGI request is occurring on a secure channel, such as SSL.
2249 =head2 cookie() A simple access method to cookies
2251 The interface to HTTP cookies is the B<cookie()> method:
2253 $cookie = $q->cookie( -name => 'sessionID',
2256 -path => '/cgi-bin/database',
2257 -domain => '.capricorn.org',
2260 print $q->header(-cookie=>$cookie);
2262 B<cookie()> creates a new cookie. Its parameters include:
2268 The name of the cookie (required). This can be any string at all.
2269 Although browsers limit their cookie names to non-whitespace
2270 alphanumeric characters, CGI.pm removes this restriction by escaping
2271 and unescaping cookies behind the scenes.
2275 The value of the cookie. This can be any scalar value,
2276 array reference, or even associative array reference. For example,
2277 you can store an entire associative array into a cookie this way:
2279 $cookie=$q->cookie( -name => 'family information',
2280 -value => \%childrens_ages );
2284 The optional partial path for which this cookie will be valid, as described
2289 The optional partial domain for which this cookie will be valid, as described
2294 The optional expiration date for this cookie. The format is as described
2295 in the section on the B<header()> method:
2297 "+1h" one hour from now
2301 If set to true, this cookie will only be used within a secure
2306 The cookie created by B<cookie()> must be incorporated into the HTTP
2307 header within the string returned by the B<header()> method:
2309 print $q->header(-cookie=>$my_cookie);
2311 To create multiple cookies, give B<header()> an array reference:
2313 $cookie1 = $q->cookie( -name => 'riddle_name',
2314 -value => "The Sphynx's Question"
2316 $cookie2 = $q->cookie( -name => 'answers',
2319 print $q->header( -cookie => [ $cookie1, $cookie2 ] );
2321 To retrieve a cookie, request it by name by calling B<cookie()> method
2322 without the B<-value> parameter:
2325 $q = new CGI::Simple;
2326 $riddle = $q->cookie('riddle_name');
2327 %answers = $q->cookie('answers');
2329 Cookies created with a single scalar value, such as the "riddle_name"
2330 cookie, will be returned in that form. Cookies with array and hash
2331 values can also be retrieved.
2333 The cookie and CGI::Simple namespaces are separate. If you have a parameter
2334 named 'answers' and a cookie named 'answers', the values retrieved by
2335 B<param()> and B<cookie()> are independent of each other. However, it's
2336 simple to turn a CGI parameter into a cookie, and vice-versa:
2338 # turn a CGI parameter into a cookie
2339 $c = $q->cookie( -name=>'answers', -value=>[$q->param('answers')] );
2341 $q->param( -name=>'answers', -value=>[$q->cookie('answers')] );
2345 Returns the HTTP_COOKIE variable. Cookies have a special format, and
2346 this method call just returns the raw form (?cookie dough). See
2347 B<cookie()> for ways of setting and retrieving cooked cookies.
2349 Called with no parameters, B<raw_cookie()> returns the packed cookie
2350 structure. You can separate it into individual cookies by splitting
2351 on the character sequence "; ". Called with the name of a cookie,
2352 retrieves the B<unescaped> form of the cookie. You can use the
2353 regular B<cookie()> method to get the names, or use the raw_fetch()
2354 method from the CGI::Simmple::Cookie module.
2358 ################# Header Methods ################
2360 =head1 CREATING HTTP HEADERS
2362 Normally the first thing you will do in any CGI script is print out an
2363 HTTP header. This tells the browser what type of document to expect,
2364 and gives other optional information, such as the language, expiration
2365 date, and whether to cache the document. The header can also be
2366 manipulated for special purposes, such as server push and pay per view
2369 =head2 header() Create simple or complex HTTP headers
2375 print $q->header('image/gif');
2379 print $q->header('text/html','204 No response');
2383 print $q->header( -type => 'image/gif',
2385 -status => '402 Payment required',
2388 -charset => 'utf-7',
2389 -attachment => 'foo.gif',
2393 B<header()> returns the Content-type: header. You can provide your own
2394 MIME type if you choose, otherwise it defaults to text/html. An
2395 optional second parameter specifies the status code and a human-readable
2396 message. For example, you can specify 204, "No response" to create a
2397 script that tells the browser to do nothing at all.
2399 The last example shows the named argument style for passing arguments
2400 to the CGI methods using named parameters. Recognized parameters are
2401 B<-type>, B<-status>, B<-cookie>, B<-target>, B<-expires>, B<-nph>,
2402 B<-charset> and B<-attachment>. Any other named parameters will be
2403 stripped of their initial hyphens and turned into header fields, allowing
2404 you to specify any HTTP header you desire.
2406 For example, you can produce non-standard HTTP header fields by providing
2407 them as named arguments:
2409 print $q->header( -type => 'text/html',
2411 -cost => 'Three smackers',
2412 -annoyance_level => 'high',
2413 -complaints_to => 'bit bucket'
2416 This will produce the following non-standard HTTP header:
2419 Cost: Three smackers
2420 Annoyance-level: high
2421 Complaints-to: bit bucket
2422 Content-type: text/html
2424 Note that underscores are translated automatically into hyphens. This feature
2425 allows you to keep up with the rapidly changing HTTP "standards".
2427 The B<-type> is a key element that tell the browser how to display your
2428 document. The default is 'text/html'. Common types are:
2435 application/octet-stream
2437 The B<-status> code is the HTTP response code. The default is 200 OK. Common
2442 301 Moved Permanently
2445 307 Temporary Redirect
2451 408 Request Timed Out
2452 500 Internal Server Error
2453 503 Service Unavailable
2454 504 Gateway Timed Out
2456 The B<-expires> parameter lets you indicate to a browser and proxy server
2457 how long to cache pages for. When you specify an absolute or relative
2458 expiration interval with this parameter, some browsers and proxy servers
2459 will cache the script's output until the indicated expiration date.
2460 The following forms are all valid for the -expires field:
2462 +30s 30 seconds from now
2463 +10m ten minutes from now
2464 +1h one hour from now
2465 -1d yesterday (i.e. "ASAP!")
2468 +10y in ten years time
2469 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
2471 The B<-cookie> parameter generates a header that tells the browser to provide
2472 a "magic cookie" during all subsequent transactions with your script.
2473 Netscape cookies have a special format that includes interesting attributes
2474 such as expiration time. Use the B<cookie()> method to create and retrieve
2477 The B<-target> is for frames use
2479 The B<-nph> parameter, if set to a true value, will issue the correct
2480 headers to work with a NPH (no-parse-header) script. This is important
2481 to use with certain servers that expect all their scripts to be NPH.
2483 The B<-charset> parameter can be used to control the character set
2484 sent to the browser. If not provided, defaults to ISO-8859-1. As a
2485 side effect, this sets the charset() method as well.
2487 The B<-attachment> parameter can be used to turn the page into an
2488 attachment. Instead of displaying the page, some browsers will prompt
2489 the user to save it to disk. The value of the argument is the
2490 suggested name for the saved file. In order for this to work, you may
2491 have to set the B<-type> to 'application/octet-stream'.
2493 =head2 no_cache() Preventing browser caching of scripts
2495 Most browsers will not cache the output from CGI scripts. Every time
2496 the browser reloads the page, the script is invoked anew. However some
2497 browsers do cache pages. You can discourage this behavior using the
2498 B<no_cache()> function.
2500 $q->no_cache(1); # turn caching off by sending appropriate headers
2501 $q->no_cache(1); # do not send cache related headers.
2504 print header (-type=>'image/gif', -nph=>1);
2506 This will produce a header like the following:
2509 Server: Apache - accept no substitutes
2510 Expires: Thu, 15 Nov 2001 03:37:50 GMT
2511 Date: Thu, 15 Nov 2001 03:37:50 GMT
2513 Content-Type: image/gif
2515 Both the Pragma: no-cache header field and an Expires header that corresponds
2516 to the current time (ie now) will be sent.
2518 =head2 cache() Preventing browser caching of scripts
2520 The somewhat ill named B<cache()> method is a legacy from CGI.pm. It operates
2521 the same as the new B<no_cache()> method. The difference is/was that when set
2522 it results only in the Pragma: no-cache line being printed.
2523 Expires time data is not sent.
2525 =head2 redirect() Generating a redirection header
2527 print $q->redirect('http://somewhere.else/in/movie/land');
2529 Sometimes you don't want to produce a document yourself, but simply
2530 redirect the browser elsewhere, perhaps choosing a URL based on the
2531 time of day or the identity of the user.
2533 The B<redirect()> function redirects the browser to a different URL. If
2534 you use redirection like this, you should B<not> print out a header as
2537 One hint I can offer is that relative links may not work correctly
2538 when you generate a redirection to another document on your site.
2539 This is due to a well-intentioned optimization that some servers use.
2540 The solution to this is to use the full URL (including the http: part)
2541 of the document you are redirecting to.
2543 You can also use named arguments:
2545 print $q->redirect( -uri=>'http://somewhere.else/in/movie/land',
2549 The B<-nph> parameter, if set to a true value, will issue the correct
2550 headers to work with a NPH (no-parse-header) script. This is important
2551 to use with certain servers, such as Microsoft ones, which
2552 expect all their scripts to be NPH.
2558 There are a number of pragmas that you can specify in your use CGI::Simple
2559 statement. Pragmas, which are always preceded by a hyphen, change the way
2560 that CGI::Simple functions in various ways. You can generally achieve
2561 exactly the same results by setting the underlying $GLOBAL_VARIABLES.
2563 For example the '-upload' pargma will enable file uploads:
2565 use CGI::Simple qw(-upload);
2567 In CGI::Simple::Standard Pragmas, function sets , and individual functions
2568 can all be imported in the same use() line. For example, the following
2569 use statement imports the standard set of functions and enables debugging
2570 mode (pragma -debug):
2572 use CGI::Simple::Standard qw(:standard -debug);
2574 The current list of pragmas is as follows:
2578 =item -no_undef_params
2580 If a value is not given in the query string, as in the queries
2581 "name1=&name2=" or "name1&name2", by default it will be returned
2584 If you specify the '-no_undef_params' pragma then CGI::Simple ignores
2585 parameters with no values and they will not appear in the query object.
2589 This makes CGI.pm produce a header appropriate for an NPH (no
2590 parsed header) script. You may need to do other things as well
2591 to tell the server that the script is NPH. See the discussion
2592 of NPH scripts below.
2594 =item -newstyle_urls
2596 Separate the name=value pairs in CGI parameter query strings with
2597 semicolons rather than ampersands. For example:
2599 ?name=fred;age=24;favorite_color=3
2601 Semicolon-delimited query strings are always accepted, but will not be
2602 emitted by self_url() and query_string() unless the -newstyle_urls
2603 pragma is specified.
2605 =item -oldstyle_urls
2607 Separate the name=value pairs in CGI parameter query strings with
2608 ampersands rather than semicolons. This is the default.
2610 ?name=fred&age=24&favorite_color=3
2614 This is only available for CGI::Simple::Standard and uses AUTOLOAD to
2615 load functions on demand. See the CGI::Simple::Standard docs for details.
2619 This turns off the command-line processing features. This is the default.
2621 =item -debug1 and debug2
2623 This turns on debugging. At debug level 1 CGI::Simple will read arguments
2624 from the command-line. At debug level 2 CGI.pm will produce the prompt
2625 "(offline mode: enter name=value pairs on standard input)" and wait for
2626 input on STDIN. If no number is specified then a debug level of 2 is used.
2628 See the section on debugging for more details.
2632 This sets the default global values for CGI.pm which will enable infinite
2633 size file uploads, and specify the '-newstyle_urls' and '-debug1' pragmas
2637 Disable uploads - the default setting
2641 Enable uploads - the CGI.pm default
2643 =item -unique_header
2645 Only allows headers to be generated once per script invocation
2649 Carp when B<cgi_error()> called, default is to do nothing
2653 Croak when B<cgi_error()> called, default is to do nothing
2659 ############### NPH Scripts ################
2661 =head1 USING NPH SCRIPTS
2663 NPH, or "no-parsed-header", scripts bypass the server completely by
2664 sending the complete HTTP header directly to the browser. This has
2665 slight performance benefits, but is of most use for taking advantage
2666 of HTTP extensions that are not directly supported by your server,
2667 such as server push and PICS headers.
2669 Servers use a variety of conventions for designating CGI scripts as
2670 NPH. Many Unix servers look at the beginning of the script's name for
2671 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's
2672 Internet Information Server, in contrast, try to decide whether a
2673 program is an NPH script by examining the first line of script output.
2675 CGI.pm supports NPH scripts with a special NPH mode. When in this
2676 mode, CGI.pm will output the necessary extra header information when
2677 the B<header()> and B<redirect()> methods are called. You can set NPH mode
2678 in any of the following ways:
2682 =item In the B<use> statement
2684 Simply add the "-nph" pragma to the use:
2686 use CGI::Simple qw(-nph)
2688 =item By calling the B<nph()> method:
2690 Call B<nph()> with a non-zero parameter at any point after using CGI.pm in your program.
2694 =item By using B<-nph> parameters
2696 in the B<header()> and B<redirect()> statements:
2698 print $q->header(-nph=>1);
2702 The Microsoft Internet Information Server requires NPH mode.
2703 CGI::Simple will automatically detect when the script is
2704 running under IIS and put itself into this mode. You do not need to
2705 do this manually, although it won't hurt anything if you do. However,
2706 note that if you have applied Service Pack 6, much of the
2707 functionality of NPH scripts, including the ability to redirect while
2708 setting a cookie, b<do not work at all> on IIS without a special patch
2710 http://support.microsoft.com/support/kb/articles/Q280/3/41.ASP:
2711 Non-Parsed Headers Stripped From CGI Applications That Have nph-
2716 ################# Server Push Methods #################
2720 CGI.pm provides four simple functions for producing multipart
2721 documents of the type needed to implement server push. These
2722 functions were graciously provided by Ed Jordan <ed@fidalgo.net> with
2723 additions from Andrew Benham <adsb@bigfoot.com>
2725 You are also advised to put the script into NPH mode and to set $| to
2726 1 to avoid buffering problems.
2728 Browser support for server push is variable.
2730 Here is a simple script that demonstrates server push:
2732 #!/usr/local/bin/perl
2733 use CGI::Simple::Standard qw/:push -nph/;
2735 print multipart_init(-boundary=>'----here we go!');
2737 print multipart_start(-type=>'text/plain'),
2738 "The current time is ",scalar(localtime),"\n";
2740 print multipart_end;
2743 print multipart_final;
2748 This script initializes server push by calling B<multipart_init()>.
2749 It then enters a loop in which it begins a new multipart section by
2750 calling B<multipart_start()>, prints the current local time,
2751 and ends a multipart section with B<multipart_end()>. It then sleeps
2752 a second, and begins again. On the final iteration, it ends the
2753 multipart section with B<multipart_final()> rather than with
2756 =head2 multipart_init() Initialize the multipart system
2758 multipart_init(-boundary=>$boundary);
2760 Initialize the multipart system. The -boundary argument specifies
2761 what MIME boundary string to use to separate parts of the document.
2762 If not provided, CGI.pm chooses a reasonable boundary for you.
2764 =head2 multipart_start() Start a new part of the multipart document
2766 multipart_start(-type=>$type)
2768 Start a new part of the multipart document using the specified MIME
2769 type. If not specified, text/html is assumed.
2771 =head2 multipart_end() End a multipart part
2775 End a part. You must remember to call B<multipart_end()> once for each
2776 B<multipart_start()>, except at the end of the last part of the multipart
2777 document when B<multipart_final()> should be called instead of
2780 =head2 multipart_final()
2784 End all parts. You should call B<multipart_final()> rather than
2785 B<multipart_end()> at the end of the last part of the multipart document.
2789 Users interested in server push applications should also have a look
2790 at the B<CGI::Push> module.
2794 ################# Debugging Methods ################
2798 If you are running the script from the command line or in the perl
2799 debugger, you can pass the script a list of keywords or
2800 parameter=value pairs on the command line or from standard input (you
2801 don't have to worry about tricking your script into reading from
2802 environment variables). Before you do this you will need to change the
2803 debug level from the default level of 0 (no debug) to either 1 if you
2804 want to debug from @ARGV (the command line) of 2 if you want to debug from
2805 STDIN. You can do this using the debug pragma like this:
2807 use CGI::Simple qw(-debug2); # set debug to level 2 => from STDIN
2811 $CGI::Simple::DEBUG = 1; # set debug to level 1 => from @ARGV
2813 At debug level 1 you can pass keywords and name=value pairs like this:
2815 your_script.pl keyword1 keyword2 keyword3
2819 your_script.pl keyword1+keyword2+keyword3
2823 your_script.pl name1=value1 name2=value2
2827 your_script.pl name1=value1&name2=value2
2829 At debug level 2 you can feed newline-delimited name=value
2830 pairs to the script on standard input. You will be presented
2831 with the following prompt:
2833 (offline mode: enter name=value pairs on standard input)
2835 You end the input with your system dependent end of file character.
2836 You should try ^Z ^X ^D and ^C if all else fails. The ^ means hold down
2837 the [Ctrl] button while you press the other key.
2839 When debugging, you can use quotes and backslashes to escape
2840 characters in the familiar shell manner, letting you place
2841 spaces and other funny characters in your parameter=value
2844 your_script.pl "name1='I am a long value'" "name2=two\ words"
2846 =head2 Dump() Dumping the current object details
2848 The B<Dump()> method produces a string consisting of all the
2849 query's object attributes formatted nicely as a nested list. This dump
2850 includes the name/value pairs and a number of other details. This is useful
2851 for debugging purposes:
2855 The actual result of this is HTML escaped formatted text wrapped in <pre> tags
2856 so if you send it straight to the browser it produces something that looks
2868 'POST_MAX' => 102400,
2869 'USE_CGI_PM_DEFAULTS' => 0,
2870 'HEADERS_ONCE' => 0,
2872 'DISABLE_UPLOADS' => 1,
2873 'NO_UNDEF_PARAMS' => 0,
2874 'USE_PARAM_SEMICOLONS' => 0
2891 You may recognize this as valid Perl syntax (which it is) and/or the output
2892 from Data::Dumper (also true). This is the actual guts of how the information
2893 is stored in the query object. All the internal params start with a . char
2895 Alternatively you can dump your object and the current environment using:
2897 print $q->Dump(\%ENV);
2899 =head2 PrintEnv() Dumping the environment
2901 You can get a similar browser friendly dump of the current %ENV hash using:
2905 This will produce something like (in the browser):
2908 'QUERY_STRING' => 'name=JaPh%2C&color=red&color=green&color=blue',
2909 'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
2910 'REGRESSION_TEST' => 'simple.t.pl',
2911 'VIM' => 'C:\\WINDOWS\\Desktop\\vim',
2912 'HTTP_REFERER' => 'xxx.sex.com',
2913 'HTTP_USER_AGENT' => 'LWP',
2914 'HTTP_ACCEPT' => 'text/html;q=1, image/gif;q=0.42, */*;q=0.001',
2915 'REMOTE_HOST' => 'localhost',
2916 'HTTP_HOST' => 'the.restaurant.at.the.end.of.the.universe',
2917 'GATEWAY_INTERFACE' => 'bleeding edge',
2918 'REMOTE_IDENT' => 'None of your damn business',
2919 'SCRIPT_NAME' => '/cgi-bin/foo.cgi',
2920 'SERVER_NAME' => 'nowhere.com',
2921 'HTTP_COOKIE' => '',
2922 'CONTENT_LENGTH' => '42',
2924 'HTTP_FROM' => 'spammer@nowhere.com',
2926 'SERVER_PROTOCOL' => 'HTTP/1.0',
2927 'PATH_TRANSLATED' => '/usr/local/somewhere/else',
2928 'SERVER_SOFTWARE' => 'Apache - accept no substitutes',
2929 'PATH_INFO' => '/somewhere/else',
2930 'REMOTE_USER' => 'Just another Perl hacker,',
2931 'REMOTE_ADDR' => '127.0.0.1',
2933 'DOCUMENT_ROOT' => '/vs/www/foo',
2934 'REQUEST_METHOD' => 'GET',
2935 'REDIRECT_QUERY_STRING' => '',
2936 'AUTH_TYPE' => 'PGP MD5 DES rot13',
2937 'COOKIE' => 'foo=a%20phrase; bar=yes%2C%20a%20phrase&;I%20say;',
2938 'SERVER_PORT' => '8080'
2942 =head2 cgi_error() Retrieving CGI::Simple error messages
2944 Errors can occur while processing user input, particularly when
2945 processing uploaded files. When these errors occur, CGI::Simple will stop
2946 processing and return an empty parameter list. You can test for
2947 the existence and nature of errors using the B<cgi_error()> function.
2948 The error messages are formatted as HTTP status codes. You can either
2949 incorporate the error text into an HTML page, or use it as the value
2952 my $error = $q->cgi_error;
2954 print $q->header(-status=>$error);
2955 print "<H2>$error</H2>;
2961 ############### Accessor Methods ################
2963 =head1 ACCESSOR METHODS
2965 =head2 version() Get the CGI::Simple version info
2967 $version = $q->version();
2969 The B<version()> method returns the value of $VERSION
2971 =head2 nph() Enable/disable NPH (Non Parsed Header) mode
2973 $q->nph(1); # enable NPH mode
2974 $q->nph(0); # disable NPH mode
2976 The B<nph()> method enables and disables NPH headers. See the NPH section.
2978 =head2 all_parameters() Get the names/values of all parameters
2980 @all_parameters = $q->all_parameters();
2982 The B<all_parameters()> method is an alias for B<param()>
2984 =head2 charset() Get/set the current character set.
2986 $charset = $q->charset(); # get current charset
2987 $q->charset('utf-42'); # set the charset
2989 The B<charset()> method gets the current charset value if no argument is
2990 supplied or sets it if an argument is supplied.
2992 =head2 crlf() Get the system specific line ending sequence
2996 The B<crlf()> method returns the system specific line ending sequence.
2998 =head2 globals() Get/set the value of the remaining global variables
3000 $globals = $q->globals('FATAL'); # get the current value of $FATAL
3001 $globals = $q->globals('FATAL', 1 ); # set croak mode on cgi_error()
3003 The B<globals()> method gets/sets the values of the global variables after the
3004 script has been invoked. For globals like $POST_MAX and $DISABLE_UPLOADS this
3005 makes no difference as they must be set prior to calling the new constructor
3006 but there might be reason the change the value of others.
3008 =head2 auth_type() Get the current authorization/verification method
3010 $auth_type = $q->auth_type();
3012 The B<auth_type()> method returns the value of $ENV{'AUTH_TYPE'} which should
3013 contain the authorization/verification method in use for this script, if any.
3015 =head2 content_length() Get the content length submitted in a POST
3017 $content_length = $q->content_length();
3019 The B<content_length()> method returns the value of $ENV{'AUTH_TYPE'}
3021 =head2 content_type() Get the content_type of data submitted in a POST
3023 $content_type = $q->content_type();
3025 The B<content_type()> method returns the content_type of data submitted in
3026 a POST, generally 'multipart/form-data' or
3027 'application/x-www-form-urlencoded' as supplied in $ENV{'CONTENT_TYPE'}
3029 =head2 document_root() Get the document root
3031 $document_root = $q->document_root();
3033 The B<document_root()> method returns the value of $ENV{'DOCUMENT_ROOT'}
3035 =head2 gateway_interface() Get the gateway interface
3037 $gateway_interface = $q->gateway_interface();
3039 The B<gateway_interface()> method returns the value of
3040 $ENV{'GATEWAY_INTERFACE'}
3042 =head2 path_translated() Get the value of path translated
3044 $path_translated = $q->path_translated();
3046 The B<path_translated()> method returns the value of $ENV{'PATH_TRANSLATED'}
3048 =head2 referer() Spy on your users
3050 $referer = $q->referer();
3052 The B<referer()> method returns the value of $ENV{'REFERER'} This will return
3053 the URL of the page the browser was viewing prior to fetching your script.
3054 Not available for all browsers.
3056 =head2 remote_addr() Get the remote address
3058 $remote_addr = $q->remote_addr();
3060 The B<remote_addr()> method returns the value of $ENV{'REMOTE_ADDR'} or
3061 127.0.0.1 (localhost) if this is not defined.
3063 =head2 remote_host() Get a value for remote host
3065 $remote_host = $q->remote_host();
3067 The B<remote_host()> method returns the value of $ENV{'REMOTE_HOST'} if it is
3068 defined. If this is not defined it returns $ENV{'REMOTE_ADDR'} If this is not
3069 defined it returns 'localhost'
3071 =head2 remote_ident() Get the remote identity
3073 $remote_ident = $q->remote_ident();
3075 The B<remote_ident()> method returns the value of $ENV{'REMOTE_IDENT'}
3077 =head2 remote_user() Get the remote user
3079 $remote_user = $q->remote_user();
3081 The B<remote_user()> method returns the authorization/verification name used
3082 for user verification, if this script is protected. The value comes from
3085 =head2 request_method() Get the request method
3087 $request_method = $q->request_method();
3089 The B<request_method()> method returns the method used to access your
3090 script, usually one of 'POST', 'GET' or 'HEAD' as supplied by
3091 $ENV{'REQUEST_METHOD'}
3093 =head2 script_name() Get the script name
3095 $script_name = $q->script_name();
3097 The B<script_name()> method returns the value of $ENV{'SCRIPT_NAME'} if it is
3098 defined. Otherwise it returns Perl's script name from $0. Failing this it
3099 returns a null string ''
3101 =head2 server_name() Get the server name
3103 $server_name = $q->server_name();
3105 The B<server_name()> method returns the value of $ENV{'SERVER_NAME'} if defined
3106 or 'localhost' otherwise
3108 =head2 server_port() Get the port the server is listening on
3110 $server_port = $q->server_port();
3112 The B<server_port()> method returns the value $ENV{'SERVER_PORT'} if defined or
3115 =head2 server_protocol() Get the current server protocol
3117 $server_protocol = $q->server_protocol();
3119 The B<server_protocol()> method returns the value of $ENV{'SERVER_PROTOCOL'} if
3120 defined or 'HTTP/1.0' otherwise
3122 =head2 server_software() Get the server software
3124 $server_software = $q->server_software();
3126 The B<server_software()> method returns the value $ENV{'SERVER_SOFTWARE'} or
3127 'cmdline' If the server software is IIS it formats your hard drive, installs
3128 Linux, FTPs to www.apache.org, installs Apache, and then restores your system
3129 from tape. Well maybe not, but it's a nice thought.
3131 =head2 user_name() Get a value for the user name.
3133 $user_name = $q->user_name();
3135 Attempt to obtain the remote user's name, using a variety of different
3136 techniques. This only works with older browsers such as Mosaic.
3137 Newer browsers do not report the user name for privacy reasons!
3139 Technically the B<user_name()> method returns the value of $ENV{'HTTP_FROM'}
3140 or failing that $ENV{'REMOTE_IDENT'} or as a last choice $ENV{'REMOTE_USER'}
3142 =head2 user_agent() Get the users browser type
3144 $ua = $q->user_agent(); # return the user agent
3145 $ok = $q->user_agent('mozilla'); # return true if user agent 'mozilla'
3147 The B<user_agent()> method returns the value of $ENV{'HTTP_USER_AGENT'} when
3148 called without an argument or true or false if the $ENV{'HTTP_USER_AGENT'}
3149 matches the passed argument. The matching is case insensitive and partial.
3151 =head2 virtual_host() Get the virtual host
3153 $virtual_host = $q->virtual_host();
3155 The B<virtual_host()> method returns the value of $ENV{'HTTP_HOST'} if defined
3156 or $ENV{'SERVER_NAME'} as a default. Port numbers are removed.
3158 =head2 path_info() Get any extra path info set to the script
3160 $path_info = $q->path_info();
3162 The B<path_info()> method returns additional path information from the script
3163 URL. E.G. fetching /cgi-bin/your_script/additional/stuff will result in
3164 $q->path_info() returning "/additional/stuff".
3166 NOTE: The Microsoft Internet Information Server
3167 is broken with respect to additional path information. If
3168 you use the Perl DLL library, the IIS server will attempt to
3169 execute the additional path information as a Perl script.
3170 If you use the ordinary file associations mapping, the
3171 path information will be present in the environment,
3172 but incorrect. The best thing to do is to avoid using additional
3173 path information in CGI scripts destined for use with IIS.
3175 =head2 Accept() Get the browser MIME types
3177 $Accept = $q->Accept();
3179 The B<Accept()> method returns a list of MIME types that the remote browser
3180 accepts. If you give this method a single argument corresponding to a
3181 MIME type, as in $q->Accept('text/html'), it will return a floating point
3182 value corresponding to the browser's preference for this type from 0.0
3183 (don't want) to 1.0. Glob types (e.g. text/*) in the browser's accept
3184 list are handled correctly.
3186 =head2 accept() Alias for Accept()
3188 $accept = $q->accept();
3190 The B<accept()> Method is an alias for Accept()
3192 =head2 http() Get a range of HTTP related information
3196 Called with no arguments the B<http()> method returns the list of HTTP or HTTPS
3197 environment variables, including such things as HTTP_USER_AGENT,
3198 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
3199 like-named HTTP header fields in the request. Called with the name of
3200 an HTTP header field, returns its value. Capitalization and the use
3201 of hyphens versus underscores are not significant.
3203 For example, all three of these examples are equivalent:
3205 $requested_language = $q->http('Accept-language');
3206 $requested_language = $q->http('Accept_language');
3207 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
3209 =head2 https() Get a range of HTTPS related information
3211 $https = $q->https();
3213 The B<https()> method is similar to the http() method except that when called
3214 without an argument it returns the value of $ENV{'HTTPS'} which will be
3215 true if a HTTPS connection is in use and false otherwise.
3217 =head2 protocol() Get the current protocol
3219 $protocol = $q->protocol();
3221 The B<protocol()> method returns 'https' if a HTTPS connection is in use or the
3222 B<server_protocol()> minus version numbers ('http') otherwise.
3224 =head2 url() Return the script's URL in several formats
3226 $full_url = $q->url();
3227 $full_url = $q->url(-full=>1);
3228 $relative_url = $q->url(-relative=>1);
3229 $absolute_url = $q->url(-absolute=>1);
3230 $url_with_path = $q->url(-path_info=>1);
3231 $url_with_path_and_query = $q->url(-path_info=>1,-query=>1);
3232 $netloc = $q->url(-base => 1);
3234 B<url()> returns the script's URL in a variety of formats. Called
3235 without any arguments, it returns the full form of the URL, including
3236 host name and port number
3238 http://your.host.com/path/to/script.cgi
3240 You can modify this format with the following named arguments:
3246 If true, produce an absolute URL, e.g.
3252 Produce a relative URL. This is useful if you want to reinvoke your
3253 script with different parameters. For example:
3259 Produce the full URL, exactly as if called without any arguments.
3260 This overrides the -relative and -absolute arguments.
3262 =item B<-path> (B<-path_info>)
3264 Append the additional path information to the URL. This can be
3265 combined with B<-full>, B<-absolute> or B<-relative>. B<-path_info>
3266 is provided as a synonym.
3268 =item B<-query> (B<-query_string>)
3270 Append the query string to the URL. This can be combined with
3271 B<-full>, B<-absolute> or B<-relative>. B<-query_string> is provided
3276 Generate just the protocol and net location, as in http://www.foo.com:8000
3280 =head2 self_url() Get the scripts complete URL
3282 $self_url = $q->self_url();
3284 The B<self_url()> method returns the value of:
3286 $self->url( '-path_info'=>1, '-query'=>1, '-full'=>1 );
3288 =head2 state() Alias for self_url()
3290 $state = $q->state();
3292 The B<state()> method is an alias for self_url()
3296 ################# cgi-lib.pl Compatibility Methods #################
3298 =head1 COMPATIBILITY WITH cgi-lib.pl 2.18
3300 To make it easier to port existing programs that use cgi-lib.pl all
3301 the subs within cgi-lib.pl are available in CGI::Simple. Using the
3302 functional interface of CGI::Simple::Standard porting is
3306 require "cgi-lib.pl";
3308 print "The value of the antique is $in{'antique'}.\n";
3311 use CGI::Simple::Standard qw(:cgi-lib);
3313 print "The value of the antique is $in{'antique'}.\n";
3315 CGI:Simple's B<ReadParse()> routine creates a variable named %in,
3316 which can be accessed to obtain the query variables. Like
3317 ReadParse, you can also provide your own variable via a glob. Infrequently
3318 used features of B<ReadParse()>, such as the creation of @in and $in
3319 variables, are not supported.
3321 You can also use the OO interface of CGI::Simple and call B<ReadParse()> and
3322 other cgi-lib.pl functions like this:
3324 &CGI::Simple::ReadParse; # get hash values in %in
3326 my $q = new CGI::Simple;
3327 $q->ReadParse(); # same thing
3329 CGI::Simple::ReadParse(*field); # get hash values in %field function style
3331 my $q = new CGI::Simple;
3332 $q->ReadParse(*field); # same thing
3334 Once you use B<ReadParse()> under the functional interface , you can retrieve
3335 the query object itself this way if needed:
3339 Either way it allows you to start using the more interesting features
3340 of CGI.pm without rewriting your old scripts from scratch.
3342 Unlike CGI.pm all the cgi-lib.pl functions from Version 2.18 are supported:
3359 =head1 COMPATIBILITY WITH CGI.pm
3361 I has long been suggested that the CGI and HTML parts of CGI.pm should be
3362 split into separate modules (even the author suggests this!), CGI::Simple
3363 represents the realization of this and contains the complete CGI side of
3364 CGI.pm. Code-wise it weighs in at a little under 30% of the size of CGI.pm at
3365 a little under 1000 lines.
3367 A great deal of care has been taken to ensure that the interface remains
3368 unchanged although a few tweaks have been made. The test suite is extensive
3369 and includes all the CGI.pm test scripts as well as a series of new test
3370 scripts. You may like to have a look at /t/concur.t which makes 160 tests
3371 of CGI::Simple and CGI in parallel and compares the results to ensure they
3372 are identical. This is the case as of CGI.pm 2.78.
3374 You can't make an omelet without breaking eggs. A large number of methods
3375 and global variables have been deleted as detailed below. Some pragmas are
3376 also gone. In the tarball there is a script B</misc/check.pl> that will check if
3377 a script seems to be using any of these now non existent methods, globals or
3378 pragmas. You call it like this:
3380 perl check.pl <files>
3382 If it finds any likely candidates it will print a line with the line number,
3383 problem method/global and the complete line. For example here is some output
3384 from running the script on CGI.pm:
3387 3162: Problem:'$CGI::OS' local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
3388 3165: Problem:'fillBuffer' $self->fillBuffer($FILLUNIT);
3391 =head1 DIFFERENCES FROM CGI.pm
3393 CGI::Simple is strict and warnings compliant.
3395 There are 4 modules in this distribution:
3397 CGI/Simple.pm supplies all the core code.
3398 CGI/Simple/Cookie.pm supplies the cookie handling functions.
3399 CGI/Simple/Util.pm supplies a variety of utility functions
3400 CGI/Simple/Standard.pm supplies a functional interface for Simple.pm
3402 Simple.pm is the core module that provide all the essential functionality.
3403 Cookie.pm is a shortened rehash of the CGI.pm module of the same name
3404 which supplies the required cookie functionality. Util.pm has been recoded to
3405 use an internal object for data storage and supplies rarely needed non core
3406 functions and/or functions needed for the HTML side of things. Standard.pm is
3407 a wrapper module that supplies a complete functional interface to the OO
3408 back end supplied by CGI::Simple.
3410 Although a serious attempt has been made to keep the interface identical,
3411 some minor changes and tweaks have been made. They will likely be
3412 insignificant to most users but here are the gory details.
3414 =head2 Globals Variables
3416 The list of global variables has been pruned by 75%. Here is the complete
3417 list of the global variables used:
3420 # set this to 1 to use CGI.pm default global settings
3421 $USE_CGI_PM_DEFAULTS = 0 unless defined $USE_CGI_PM_DEFAULTS;
3422 # see if user wants old CGI.pm defaults
3423 do{ _use_cgi_pm_global_settings(); return } if $USE_CGI_PM_DEFAULTS;
3424 # no file uploads by default, set to 0 to enable uploads
3425 $DISABLE_UPLOADS = 1 unless defined $DISABLE_UPLOADS;
3426 # use a post max of 100K, set to -1 for no limits
3427 $POST_MAX = 102_400 unless defined $POST_MAX;
3428 # do not include undefined params parsed from query string
3429 $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS;
3430 # separate the name=value pairs with ; rather than &
3431 $USE_PARAM_SEMICOLONS = 0 unless defined $USE_PARAM_SEMICOLONS;
3432 # only print headers once
3433 $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE;
3434 # Set this to 1 to enable NPH scripts
3435 $NPH = 0 unless defined $NPH;
3436 # 0 => no debug, 1 => from @ARGV, 2 => from STDIN
3437 $DEBUG = 0 unless defined $DEBUG;
3438 # filter out null bytes in param - value pairs
3439 $NO_NULL = 1 unless defined $NO_NULL;
3440 # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak
3441 $FATAL = -1 unless defined $FATAL;
3443 Four of the default values of the old CGI.pm variables have been changed.
3444 Unlike CGI.pm which by default allows unlimited POST data and file uploads
3445 by default CGI::Simple limits POST data size to 100kB and denies file uploads
3446 by default. $USE_PARAM_SEMICOLONS is set to 0 by default so we use (old style)
3447 & rather than ; as the pair separator for query strings. Debugging is
3448 disabled by default.
3450 There are three new global variables. If $NO_NULL is true (the default) then
3451 CGI::Simple will strip null bytes out of names, values and keywords. Null
3452 bytes can do interesting things to C based code like Perl. Uploaded files
3453 are not touched. $FATAL controls the behavior when B<cgi_error()> is called.
3454 The default value of -1 makes errors silent. $USE_CGI_PM_DEFAULTS reverts the
3455 defaults to the CGI.pm standard values ie unlimited file uploads via POST
3456 for DNS attacks. You can also get the defaults back by using the '-default'
3459 use CGI::Simple qw(-default);
3460 use CGI::Simple::Standard qw(-default);
3462 The values of the global variables are stored in the CGI::Simple object and
3463 can be referenced and changed using the B<globals()> method like this:
3465 my $value = $q->globals( 'VARNAME' ); # get
3466 $q->globals( 'VARNAME', 'some value' ); # set
3468 As with many CGI.pm methods if you pass the optional value that will
3471 The $CGI::Simple::VARNAME = 'N' syntax is only useful prior to calling the
3472 B<new()> constructor. After that all reference is to the values stored in the
3473 CGI::Simple object so you must change these using the B<globals()> method.
3475 $DISABLE_UPLOADS and $POST_MAX *must* be set prior to calling the constructor
3476 if you want the changes to have any effect as they control behavior during
3477 initialization. This is the same a CGI.pm although some people seem to miss
3478 this rather important point and set these after calling the constructor which
3481 The following globals are no longer relevant and have all been deleted:
3483 $AUTOLOADED_ROUTINES
3520 Notes: CGI::Simple uses IO::File->new_tmpfile to get tempfile filehandles.
3521 These are private by default so $PRIVATE_TEMPFILES is no longer required nor
3522 is $TMPDIRECTORY. The value that were stored in $OS, $CRLF, $QUERY_CHARSET
3523 and $EBCDIC are now stored in the CGI::Simple::Util object where they find
3524 most of their use. The $MOD_PERL and $PERLEX values are now stored in our
3525 CGI::Simple object. $IIS was only used once in path_info(). $SL the system
3526 specific / \ : path delimiter is not required as we let IO::File handle our
3527 tempfile requirements. The rest of the globals are HTML related, export
3528 related, hand rolled autoload related or serve obscure purposes in CGI.pm
3530 =head2 Changes to pragmas
3532 There are some new pragmas available. See the pragmas section for details.
3533 The following CGI.pm pragmas are not available:
3543 Unlike CGI.pm which tries to accept all filehandle like objects only \*FH
3544 and $fh are accepted by CGI::Simple as file accessors for B<new()> and B<save()>.
3545 IO::File objects work fine.
3547 =head2 Hash interface
3549 %hash = $q->Vars(); # pack values with "\0";
3550 %hash = $q->Vars(","); # comma separate values
3552 You may optionally pass B<Vars()> a string that will be used to separate multiple
3553 values when they are packed into the single hash value. If no value is
3554 supplied the default "\0" (null byte) will be used. Null bytes are dangerous
3555 things for C based code (ie Perl).
3559 All the cgi-lib.pl 2.18 routines are supported. Unlike CGI.pm all the
3560 subroutines from cgi-lib.pl are included. They have been GOLFED down to
3561 25 lines but they all work pretty much the same as the originals.
3563 =head1 CGI::Simple COMPLETE METHOD LIST
3565 Here is a complete list of all the CGI::Simple methods.
3567 =head2 Guts (hands off, except of course for new)
3570 _use_cgi_pm_global_settings
3603 =head2 Save and Restore from File Methods
3609 =head2 Miscellaneous Methods
3618 =head2 Cookie Methods
3623 =head2 Header Methods
3630 =head2 Server Push Methods
3637 =head2 Debugging Methods
3644 =head2 cgi-lib.pl Compatibility Routines - all 2.18 functions available
3662 =head2 Accessor Methods
3668 crlf # new, returns OS specific CRLF sequence
3669 globals # get/set global variables
3700 =head1 NEW METHODS IN CGI::Simple
3702 There are a few new methods in CGI::Simple as listed below. The highlights are
3703 the B<parse_query_string()> method to add the QUERY_STRING data to your object if
3704 the method was POST. The B<no_cache()> method adds an expires now directive and
3705 the Pragma: no-cache directive to the header to encourage some browsers to
3706 do the right thing. B<PrintEnv()> from the cgi-lib.pl routines will dump an
3707 HTML friendly list of the %ENV and makes a handy addition to B<Dump()> for use
3708 in debugging. The upload method now accepts a filepath as an optional second
3709 argument as shown in the synopsis. If this is supplied the uploaded file will
3710 be written to there automagically.
3712 =head2 Internal Routines
3714 _initialize_globals()
3715 _use_cgi_pm_global_settings()
3722 _parse_keywordlist()
3727 =head2 New Public Methods
3729 add_param() # adds a param/value(s) pair +/- overwrite
3730 upload_info() # uploaded files MIME type and size
3731 url_decode() # decode s url encoded string
3732 url_encode() # url encode a string
3733 parse_query_string() # add QUERY_STRING data to $q object if 'POST'
3734 no_cache() # add both the Pragma: no-cache
3735 # and Expires/Date => 'now' to header
3737 =head2 cgi-lib.pl methods added for completeness
3739 _shift_if_ref() # internal hack reminiscent of self_or_default :-)
3748 =head2 New Accessors
3750 crlf() # returns CRLF sequence
3751 globals() # global vars now stored in $q object - get/set
3752 content_length() # returns $ENV{'CONTENT_LENGTH'}
3753 document_root() # returns $ENV{'DOCUMENT_ROOT'}
3754 gateway_interface() # returns $ENV{'GATEWAY_INTERFACE'}
3756 =head1 METHODS IN CGI.pm NOT IN CGI::Simple
3758 Here is a complete list of what is not included in CGI::Simple. Basically all
3759 the HTML related stuff plus large redundant chunks of the guts. The check.pl
3760 script in the /misc dir will check to see if a script is using any of these.
3762 =head2 Guts - rearranged, recoded, renamed and hacked out of existence
3764 initialize_globals()
3779 new_MultipartBuffer()
3781 import_names() # I dislike this and left it out, so shoot me.
3796 end_multipart_form()
3797 start_multipart_form()
3821 =head2 Upload Related
3823 CGI::Simple uses anonymous tempfiles supplied by IO::File to spool uploaded
3826 private_tempfiles() # automatic in CGI::Simple
3827 tmpFileName() # all upload files are anonymous
3828 uploadInfo() # relied on FH access, replaced with upload_info()
3831 =head2 Really Private Subs (marked as so)
3833 previous_or_default()
3834 register_parameter()
3836 _set_values_and_labels()
3841 =head2 Internal Multipart Parsing Routines
3854 =head1 AUTHOR INFORMATION
3856 Originally copyright 2001 Dr James Freeman E<lt>jfreeman@tassie.net.auE<gt>
3857 This release by Andy Armstrong <andy@hexten.net>
3859 This package is free software and is provided "as is" without express or
3860 implied warranty. It may be used, redistributed and/or modified under the terms
3861 of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html)
3863 Address bug reports and comments to: andy@hexten.net. When sending
3864 bug reports, please provide the version of CGI::Simple, the version of
3865 Perl, the name and version of your Web server, and the name and
3866 version of the operating system you are using. If the problem is even
3867 remotely browser dependent, please provide information about the
3868 affected browsers as well.
3870 Address bug reports and comments to: andy@hexten.net
3874 Lincoln D. Stein (lstein@cshl.org) and everyone else who worked on the
3875 original CGI.pm upon which this module is heavily based
3877 Brandon Black for some heavy duty testing and bug fixes
3879 John D Robinson and Jeroen Latour for helping solve some interesting test
3880 failures as well as Perlmonks:
3881 tommyw, grinder, Jaap, vek, erasei, jlongino and strider_corinth
3883 Thanks for patches to:
3885 Ewan Edwards, Joshua N Pritikin, Mike Barry
3887 =head1 LICENCE AND COPYRIGHT
3889 Copyright (c) 2007, Andy Armstrong C<< <andy@hexten.net> >>. All rights reserved.
3891 This module is free software; you can redistribute it and/or
3892 modify it under the same terms as Perl itself. See L<perlartistic>.
3896 B<CGI>, L<CGI::Simple::Standard>, L<CGI::Simple::Cookie>,
3897 L<CGI::Simple::Util>, L<CGI::Minimal>