1Simple(3) User Contributed Perl Documentation Simple(3)
2
3
4
6 CGI::Simple - A Simple totally OO CGI interface that is CGI.pm compli‐
7 ant
8
10 use CGI::Simple;
11 $CGI::Simple::POST_MAX = 1024; # max upload via post default 100kB
12 $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads
13
14 $q = new CGI::Simple;
15 $q = new CGI::Simple( { 'foo'=>'1', 'bar'=>[2,3,4] } );
16 $q = new CGI::Simple( 'foo=1&bar=2&bar=3&bar=4' );
17 $q = new CGI::Simple( \*FILEHANDLE );
18
19 $q->save( \*FILEHANDLE ); # save current object to a file as used by new
20
21 @params = $q->param; # return all param names as a list
22 $value = $q->param('foo'); # return the first value supplied for 'foo'
23 @values = $q->param('foo'); # return all values supplied for foo
24
25 %fields = $q->Vars; # returns untied key value pair hash
26 $hash_ref = $q->Vars; # or as a hash ref
27 %fields = $q->Vars("⎪"); # packs multiple values with "⎪" rather than "\0";
28
29 @keywords = $q->keywords; # return all keywords as a list
30
31 $q->param( 'foo', 'some', 'new', 'values' ); # set new 'foo' values
32 $q->param( -name=>'foo', -value=>'bar' );
33 $q->param( -name=>'foo', -value=>['bar','baz'] );
34
35 $q->param( 'foo', 'some', 'new', 'values' ); # append values to 'foo'
36 $q->append( -name=>'foo', -value=>'bar' );
37 $q->append( -name=>'foo', -value=>['some', 'new', 'values'] );
38
39 $q->delete('foo'); # delete param 'foo' and all its values
40 $q->delete_all; # delete everything
41
42 <INPUT TYPE="file" NAME="upload_file" SIZE="42">
43
44 $files = $q->upload() # number of files uploaded
45 @files = $q->upload(); # names of all uploaded files
46 $filename = $q->param('upload_file') # filename of uploaded file
47 $mime = $q->upload_info($filename,'mime'); # MIME type of uploaded file
48 $size = $q->upload_info($filename,'size'); # size of uploaded file
49
50 my $fh = $q->upload($filename); # get filehandle to read from
51 while ( read( $fh, $buffer, 1024 ) ) { ... }
52
53 # short and sweet upload
54 $ok = $q->upload( $q->param('upload_file'), '/path/to/write/file.name' );
55 print "Uploaded ".$q->param('upload_file')." and wrote it OK!" if $ok;
56
57 $decoded = $q->url_decode($encoded);
58 $encoded = $q->url_encode($unencoded);
59 $escaped = $q->escapeHTML('<>"&');
60 $unescaped = $q->unescapeHTML('<>"&');
61
62 $qs = $q->query_string; # get all data in $q as a query string OK for GET
63
64 $q->no_cache(1); # set Pragma: no-cache + expires
65 print $q->header(); # print a simple header
66 # get a complex header
67 $header = $q->header( -type => 'image/gif'
68 -nph => 1,
69 -status => '402 Payment required',
70 -expires =>'+24h',
71 -cookie => $cookie,
72 -charset => 'utf-7',
73 -attachment => 'foo.gif',
74 -Cost => '$2.00'
75 );
76 # a p3p header (OK for redirect use as well)
77 $header = $q->header( -p3p => 'policyref="http://somesite.com/P3P/PolicyReferences.xml' );
78
79 @cookies = $q->cookie(); # get names of all available cookies
80 $value = $q->cookie('foo') # get first value of cookie 'foo'
81 @value = $q->cookie('foo') # get all values of cookie 'foo'
82 # get a cookie formatted for header() method
83 $cookie = $q->cookie( -name => 'Password',
84 -values => ['superuser','god','my dog woofie'],
85 -expires => '+3d',
86 -domain => '.nowhere.com',
87 -path => '/cgi-bin/database',
88 -secure => 1
89 );
90 print $q->header( -cookie=>$cookie ); # set cookie
91
92 print $q->redirect('http://go.away.now'); # print a redirect header
93
94 dienice( $q->cgi_error ) if $q->cgi_error;
95
97 CGI::Simple provides a relatively lightweight drop in replacement for
98 CGI.pm. It shares an identical OO interface to CGI.pm for parameter
99 parsing, file upload, cookie handling and header generation. This mod‐
100 ule is entirely object oriented, however a complete functional inter‐
101 face is available by using the CGI::Simple::Standard module.
102
103 Essentially everything in CGI.pm that relates to the CGI (not HTML)
104 side of things is available. There are even a few new methods and addi‐
105 tions to old ones! If you are interested in what has gone on under the
106 hood see the Compatibility with CGI.pm section at the end.
107
108 In practical testing this module loads and runs about twice as fast as
109 CGI.pm depending on the precise task.
110
112 Here is a very brief rundown on how you use the interface. Full details
113 follow.
114
115 First you need to initialize an object
116
117 Before you can call a CGI::Simple method you must create a CGI::Simple
118 object. You do that by using the module and then calling the new()
119 constructor:
120
121 use CGI::Simple;
122 my $q = new CGI::Simple;
123
124 It is traditional to call your object $q for query or perhaps $cgi.
125
126 Next you call methods on that object
127
128 Once you have your object you can call methods on it using the -> arrow
129 syntax For example to get the names of all the parameters passed to
130 your script you would just write:
131
132 @names = $q->param();
133
134 Many methods are sensitive to the context in which you call them. In
135 the example above the param() method returns a list of all the parame‐
136 ter names when called without any arguments.
137
138 When you call param('arg') with a single argument it assumes you want
139 to get the value(s) associated with that argument (parameter). If you
140 ask for an array it gives you an array of all the values associated
141 with it's argument:
142
143 @values = $q->param('foo'); # get all the values for 'foo'
144
145 whereas if you ask for a scalar like this:
146
147 $value = $q->param('foo'); # get only the first value for 'foo'
148
149 then it returns only the first value (if more than one value for 'foo'
150 exists).
151
152 Most CGI::Simple routines accept several arguments, sometimes as many
153 as 10 optional ones! To simplify this interface, all routines use a
154 named argument calling style that looks like this:
155
156 print $q->header( -type=>'image/gif', -expires=>'+3d' );
157
158 Each argument name is preceded by a dash. Neither case nor order mat‐
159 ters in the argument list. -type, -Type, and -TYPE are all acceptable.
160
161 Several routines are commonly called with just one argument. In the
162 case of these routines you can provide the single argument without an
163 argument name. header() happens to be one of these routines. In this
164 case, the single argument is the document type.
165
166 print $q->header('text/html');
167
168 Sometimes methods expect a scalar, sometimes a reference to an array,
169 and sometimes a reference to a hash. Often, you can pass any type of
170 argument and the routine will do whatever is most appropriate. For
171 example, the param() method can be used to set a CGI parameter to a
172 single or a multi-valued value. The two cases are shown below:
173
174 $q->param(-name=>'veggie',-value=>'tomato');
175 $q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
176
178 For convenience a functional interface is provided by the CGI::Sim‐
179 ple::Standard module. This hides the OO details from you and allows you
180 to simply call methods. You may either use AUTOLOADING of methods or
181 import specific method sets into you namespace. Here are the first few
182 examples again using the function interface.
183
184 use CGI::Simple::Standard qw(-autoload);
185 @names = param();
186 @values = param('foo');
187 $value = param('foo');
188 print header(-type=>'image/gif',-expires=>'+3d');
189 print header('text/html');
190
191 Yes that's it. Not a $q-> in sight. You just use the module and select
192 how/which methods to load. You then just call the methods you want
193 exactly as before but without the $q-> notation.
194
195 When (if) you read the following docs and are using the functional
196 interface just pretend the $q-> is not there.
197
198 Selecting which methods to load
199
200 When you use the functional interface Perl needs to be able to find the
201 functions you call. The simplest way of doing this is to use autoload‐
202 ing as shown above. When you use CGI::Simple::Standard with the
203 '-autoload' pragma it exports a single AUTOLOAD sub into you namespace.
204 Every time you call a non existent function AUTOLOAD is called and will
205 load the required function and install it in your namespace. Thus only
206 the AUTOLOAD sub and those functions you specifically call will be
207 imported.
208
209 Alternatively CGI::Simple::Standard provides a range of function sets
210 you can import or you can just select exactly what you want. You do
211 this using the familiar
212
213 use CGI::Simple::Standard qw( :func_set some_func);
214
215 notation. This will import the ':func_set' function set and the spe‐
216 cific function 'some_func'.
217
218 To Autoload or not to Autoload, that is the question.
219
220 If you do not have a AUTOLOAD sub in you script it is generally best to
221 use the '-autoload' option. Under autoload you can use any method you
222 want but only import and compile those functions you actually use.
223
224 If you do not use autoload you must specify what functions to import.
225 You can only use functions that you have imported. For comvenience
226 functions are grouped into related sets. If you choose to import one or
227 more ':func_set' you may have potential namespace collisions so check
228 out the docs to see what gets imported. Using the ':all' tag is pretty
229 slack but it is there if you want. Full details of the function sets
230 are provided in the CGI::Simple::Standard docs
231
232 If you just want say the param and header methods just load these two.
233
234 use CGI::Simple::Standard qw(param header);
235
236 Setting globals using the functional interface
237
238 Where you see global variables being set using the syntax:
239
240 $CGI::Simple::DEBUG = 1;
241
242 You use exactly the same syntax when using CGI::Simple::Standard.
243
245 new() Creating a new query object
246
247 The first step in using CGI::Simple is to create a new query object
248 using the new() constructor:
249
250 $q = new CGI::Simple;
251
252 This will parse the input (from both POST and GET methods) and store it
253 into an object called $q.
254
255 If you provide a file handle to the new() method, it will read parame‐
256 ters from the file (or STDIN, or whatever).
257
258 open FH, "test.in" or die $!;
259 $q = new CGI::Simple(\*FH);
260
261 open $fh, "test.in" or die $!;
262 $q = new CGI::Simple($fh);
263
264 The file should be a series of newline delimited TAG=VALUE pairs. Con‐
265 veniently, this type of file is created by the save() method (see
266 below). Multiple records can be saved and restored. IO::File objects
267 work fine.
268
269 If you are using the function-oriented interface provided by CGI::Sim‐
270 ple::Standard and want to initialize from a file handle, the way to do
271 this is with restore_parameters(). This will (re)initialize the
272 default CGI::Simple object from the indicated file handle.
273
274 restore_parameters(\*FH);
275
276 In fact for all intents and purposes restore_parameters() is identical
277 to new() Note that restore_parameters() does not exist in CGI::Simple
278 itself so you can't use it.
279
280 You can also initialize the query object from an associative array ref‐
281 erence:
282
283 $q = new CGI::Simple( { 'dinosaur' => 'barney',
284 'song' => 'I love you',
285 'friends' => [qw/Jessica George Nancy/] }
286 );
287
288 or from a properly formatted, URL-escaped query string:
289
290 $q = new CGI::Simple( 'dinosaur=barney&color=purple' );
291
292 or from a previously existing CGI::Simple object (this generates an
293 identical clone including all global variable settings, etc that are
294 stored in the object):
295
296 $old_query = new CGI::Simple;
297 $new_query = new CGI::Simple($old_query);
298
299 To create an empty query, initialize it from an empty string or hash:
300
301 $empty_query = new CGI::Simple("");
302
303 -or-
304
305 $empty_query = new CGI::Simple({});
306
307 keywords() Fetching a list of keywords from a query
308
309 @keywords = $q->keywords;
310
311 If the script was invoked as the result of an <ISINDEX> search, the
312 parsed keywords can be obtained as an array using the keywords()
313 method.
314
315 param() Fetching the names of all parameters passed to your script
316
317 @names = $q->param;
318
319 If the script was invoked with a parameter list (e.g.
320 "name1=value1&name2=value2&name3=value3"), the param() method will
321 return the parameter names as a list. If the script was invoked as an
322 <ISINDEX> script and contains a string without ampersands (e.g.
323 "value1+value2+value3") , there will be a single parameter named "key‐
324 words" containing the "+"-delimited keywords.
325
326 NOTE: The array of parameter names returned will be in the same order
327 as they were submitted by the browser. Usually this order is the same
328 as the order in which the parameters are defined in the form (however,
329 this isn't part of the spec, and so isn't guaranteed).
330
331 param() Fetching the value or values of a simple named parameter
332
333 @values = $q->param('foo');
334
335 -or-
336
337 $value = $q->param('foo');
338
339 Pass the param() method a single argument to fetch the value of the
340 named parameter. If the parameter is multi-valued (e.g. from multiple
341 selections in a scrolling list), you can ask to receive an array. Oth‐
342 erwise the method will return a single value.
343
344 If a value is not given in the query string, as in the queries
345 "name1=&name2=" or "name1&name2", it will be returned by default as an
346 empty string. If you set the global variable:
347
348 $CGI::Simple::NO_UNDEF_PARAMS = 1;
349
350 Then value-less parameters will be ignored, and will not exist in the
351 query object. If you try to access them via param you will get an undef
352 return value.
353
354 param() Setting the values of a named parameter
355
356 $q->param('foo','an','array','of','values');
357
358 This sets the value for the named parameter 'foo' to an array of val‐
359 ues. This is one way to change the value of a field.
360
361 param() also recognizes a named parameter style of calling described in
362 more detail later:
363
364 $q->param(-name=>'foo',-values=>['an','array','of','values']);
365
366 -or-
367
368 $q->param(-name=>'foo',-value=>'the value');
369
370 add_param() Setting the values of a named parameter
371
372 You nay also use the new method add_param to add parameters. This is an
373 alias to the _add_param() internal method that actually does all the
374 work. You can call it like this:
375
376 $q->add_param('foo', 'new');
377 $q->add_param('foo', [1,2,3,4,5]);
378 $q->add_param( 'foo', 'bar', 'overwrite' );
379
380 The first argument is the parameter, the second the value or an array
381 ref of values and the optional third argument sets overwrite mode. If
382 the third argument is absent of false the values will be appended. If
383 true the values will overwrite any existing ones
384
385 append() Appending values to a named parameter
386
387 $q->append(-name=>'foo',-values=>['yet','more','values']);
388
389 This adds a value or list of values to the named parameter. The values
390 are appended to the end of the parameter if it already exists. Other‐
391 wise the parameter is created. Note that this method only recognizes
392 the named argument calling syntax.
393
394 import_names() Importing all parameters into a namespace.
395
396 This method was silly, non OO and has been deleted. You can get all the
397 params as a hash using Vars or via all the other accessors.
398
399 delete() Deleting a parameter completely
400
401 $q->delete('foo');
402
403 This completely clears a parameter. If you are using the function call
404 interface, use Delete() instead to avoid conflicts with Perl's built-in
405 delete operator.
406
407 If you are using the function call interface, use Delete() instead to
408 avoid conflicts with Perl's built-in delete operator.
409
410 delete_all() Deleting all parameters
411
412 $q->delete_all();
413
414 This clears the CGI::Simple object completely. For CGI.pm compatibility
415 Delete_all() is provided however there is no reason to use this in the
416 function call interface other than symmetry.
417
418 For CGI.pm compatibility Delete_all() is provided as an alias for
419 delete_all however there is no reason to use this, even in the function
420 call interface.
421
422 param_fetch() Direct access to the parameter list
423
424 This method is provided for CGI.pm compatibility only. It returns an
425 array ref to the values associated with a named param. It is depre‐
426 cated.
427
428 Vars() Fetching the entire parameter list as a hash
429
430 $params = $q->Vars; # as a tied hash ref
431 print $params->{'address'};
432 @foo = split "\0", $params->{'foo'};
433
434 %params = $q->Vars; # as a plain hash
435 print $params{'address'};
436 @foo = split "\0", $params{'foo'};
437
438 %params = $q->Vars(','); # specifying a different separator than "\0"
439 @foo = split ',', $params{'foo'};
440
441 Many people want to fetch the entire parameter list as a hash in which
442 the keys are the names of the CGI parameters, and the values are the
443 parameters' values. The Vars() method does this.
444
445 Called in a scalar context, it returns the parameter list as a tied
446 hash reference. Because this hash ref is tied changing a key/value
447 changes the underlying CGI::Simple object.
448
449 Called in a list context, it returns the parameter list as an ordinary
450 hash. Changing this hash will not change the underlying CGI::Simple
451 object
452
453 When using Vars(), the thing you must watch out for are multi-valued
454 CGI parameters. Because a hash cannot distinguish between scalar and
455 list context, multi-valued parameters will be returned as a packed
456 string, separated by the "\0" (null) character. You must split this
457 packed string in order to get at the individual values. This is the
458 convention introduced long ago by Steve Brenner in his cgi-lib.pl mod‐
459 ule for Perl version 4.
460
461 You can change the character used to do the multiple value packing by
462 passing it to Vars() as an argument as shown.
463
464 url_param() Access the QUERY_STRING regardless of 'GET' or 'POST'
465
466 The url_param() method makes the QUERY_STRING data available regardless
467 of whether the REQUEST_METHOD was 'GET' or 'POST'. You can do anything
468 with url_param that you can do with param(), however the data set is
469 completely independent.
470
471 Technically what happens if you use this method is that the
472 QUERY_STRING data is parsed into a new CGI::Simple object which is
473 stored within the current object. url_param then just calls param() on
474 this new object.
475
476 parse_query_string() Add QUERY_STRING data to 'POST' requests
477
478 When the REQUEST_METHOD is 'POST' the default behavior is to ignore
479 name/value pairs or keywords in the $ENV{'QUERY_STRING'}. You can over‐
480 ride this by calling parse_query_string() which will add the
481 QUERY_STRING data to the data already in our CGI::Simple object if the
482 REQUEST_METHOD was 'POST'
483
484 $q = new CGI::Simple;
485 $q->parse_query_string; # add $ENV{'QUERY_STRING'} data to our $q object
486
487 If the REQUEST_METHOD was 'GET' then the QUERY_STRING will already be
488 stored in our object so parse_query_string will be ignored.
489
490 This is a new method in CGI::Simple that is not available in CGI.pm
491
492 save() Saving the state of an object to file
493
494 $q->save(\*FILEHANDLE)
495
496 This will write the current state of the form to the provided filehan‐
497 dle. You can read it back in by providing a filehandle to the new()
498 method.
499
500 The format of the saved file is:
501
502 NAME1=VALUE1
503 NAME1=VALUE1'
504 NAME2=VALUE2
505 NAME3=VALUE3
506 =
507
508 Both name and value are URL escaped. Multi-valued CGI parameters are
509 represented as repeated names. A session record is delimited by a sin‐
510 gle = symbol. You can write out multiple records and read them back in
511 with several calls to new().
512
513 open FH, "test.in" or die $!;
514 $q1 = new CGI::Simple(\*FH); # get the first record
515 $q2 = new CGI::Simple(\*FH); # get the next record
516
517 Note: If you wish to use this method from the function-oriented
518 (non-OO) interface, the exported name for this method is save_parame‐
519 ters(). Also if you want to initialize from a file handle, the way to
520 do this is with restore_parameters(). This will (re)initialize the
521 default CGI::Simple object from the indicated file handle.
522
523 restore_parameters(\*FH);
524
526 File uploads are easy with CGI::Simple. You use the upload() method.
527 Assuming you have the following in your HTML:
528
529 <FORM
530 METHOD="POST"
531 ACTION="http://somewhere.com/cgi-bin/script.cgi"
532 ENCTYPE="multipart/form-data">
533 <INPUT TYPE="file" NAME="upload_file1" SIZE="42">
534 <INPUT TYPE="file" NAME="upload_file2" SIZE="42">
535 </FORM>
536
537 Note that the ENCTYPE is "multipart/form-data". You must specify this
538 or the browser will default to "application/x-www-form-urlencoded"
539 which will result in no files being uploaded although on the surface
540 things will appear OK.
541
542 When the user submits this form any supplied files will be spooled onto
543 disk and saved in temporary files. These files will be deleted when
544 your script.cgi exits so if you want to keep them you will need to pro‐
545 ceed as follows.
546
547 upload() The key file upload method
548
549 The upload() method is quite versatile. If you call upload() without
550 any arguments it will return a list of uploaded files in list context
551 and the number of uploaded files in scalar context.
552
553 $number_of_files = $q->upload;
554 @list_of_files = $q->upload;
555
556 Having established that you have uploaded files available you can get
557 the browser supplied filename using param() like this:
558
559 $filename1 = $q->param('upload_file1');
560
561 You can then get a filehandle to read from by calling upload() and sup‐
562 plying this filename as an argument. Warning: do not modify the value
563 you get from param() in any way - you don't need to untaint it.
564
565 $fh = $q->upload( $filename1 );
566
567 Now to save the file you would just do something like:
568
569 $save_path = '/path/to/write/file.name';
570 open FH, ">$save_path" or die "Oops $!\n";
571 binmode FH;
572 print FH $buffer while read( $fh, $buffer, 4096 );
573 close FH;
574
575 By utilizing a new feature of the upload method this process can be
576 simplified to:
577
578 $ok = $q->upload( $q->param('upload_file1'), '/path/to/write/file.name' );
579 if ($ok) {
580 print "Uploaded and wrote file OK!";
581 } else {
582 print $q->cgi_error();
583 }
584
585 As you can see upload will accept an optional second argument and will
586 write the file to this file path. It will return 1 for success and
587 undef if it fails. If it fails you can get the error from cgi_error
588
589 You can also use just the fieldname as an argument to upload ie:
590
591 $fh = $q->upload( 'upload_field_name' );
592
593 or
594
595 $ok = $q->upload( 'upload_field_name', '/path/to/write/file.name' );
596
597 BUT there is a catch. If you have multiple upload fields, all called
598 'upload_field_name' then you will only get the last uploaded file from
599 these fields.
600
601 upload_info() Get the details about uploaded files
602
603 The upload_info() method is a new method. Called without arguments it
604 returns the number of uploaded files in scalar context and the names of
605 those files in list context.
606
607 $number_of_upload_files = $q->upload_info();
608 @filenames_of_all_uploads = $q->upload_info();
609
610 You can get the MIME type of an uploaded file like this:
611
612 $mime = $q->upload_info( $filename1, 'mime' );
613
614 If you want to know how big a file is before you copy it you can get
615 that information from uploadInfo which will return the file size in
616 bytes.
617
618 $file_size = $q->upload_info( $filename1, 'size' );
619
620 The size attribute is optional as this is the default value returned.
621
622 Note: The old CGI.pm uploadInfo() method has been deleted.
623
624 $POST_MAX and $DISABLE_UPLOADS
625
626 CGI.pm has a default setting that allows infinite size file uploads by
627 default. In contrast file uploads are disabled by default in CGI::Sim‐
628 ple to discourage Denial of Service attacks. You must enable them
629 before you expect file uploads to work.
630
631 When file uploads are disabled the file name and file size details will
632 still be available from param() and upload_info respectively but the
633 upload filehandle returned by upload() will be undefined - not surpris‐
634 ing as the underlying temp file will not exist either.
635
636 You can enable uploads using the '-upload' pragma. You do this by spec‐
637 ifying this in you use statement:
638
639 use CGI::Simple qw(-upload);
640
641 Alternatively you can enable uploads via the $DISABLE_UPLOADS global
642 like this:
643
644 use CGI::Simple;
645 $CGI::Simple::DISABLE_UPLOADS = 0;
646 $q = new CGI::Simple;
647
648 If you wish to set $DISABLE_UPLOADS you must do this *after* the use
649 statement and *before* the new constructor call as shown above.
650
651 The maximum acceptable data via post is capped at 102_400kB rather than
652 infinity which is the CGI.pm default. This should be ample for most
653 tasks but you can set this to whatever you want using the $POST_MAX
654 global.
655
656 use CGI::Simple;
657 $CGI::Simple::DISABLE_UPLOADS = 0; # enable uploads
658 $CGI::Simple::POST_MAX = 1_048_576; # allow 1MB uploads
659 $q = new CGI::Simple;
660
661 If you set to -1 infinite size uploads will be permitted, which is the
662 CGI.pm default.
663
664 $CGI::Simple::POST_MAX = -1; # infinite size upload
665
666 Alternatively you can specify all the CGI.pm default values which allow
667 file uploads of infinite size in one easy step by specifying the
668 '-default' pragma in your use statement.
669
670 use CGI::Simple qw( -default ..... );
671
672 binmode() and Win32
673
674 If you are using CGI::Simple be sure to call binmode() on any handle
675 that you create to write the uploaded file to disk. Calling binmode()
676 will do no harm on other systems anyway.
677
679 escapeHTML() Escaping HTML special characters
680
681 In HTML the < > " and & chars have special meaning and need to be
682 escaped to < > " and & respectively.
683
684 $escaped = $q->escapeHTML( $string );
685
686 $escaped = $q->escapeHTML( $string, 'new_lines_too' );
687
688 If the optional second argument is supplied then newlines will be
689 escaped to.
690
691 unescapeHTML() Unescape HTML special characters
692
693 This performs the reverse of escapeHTML().
694
695 $unescaped = $q->unescapeHTML( $HTML_escaped_string );
696
697 url_decode() Decode a URL encoded string
698
699 This method will correctly decode a url encoded string.
700
701 $decoded = $q->url_decode( $encoded );
702
703 url_encode() URL encode a string
704
705 This method will correctly URL encode a string.
706
707 $encoded = $q->url_encode( $string );
708
709 parse_keywordlist() Parse a supplied keyword list
710
711 @keywords = $q->parse_keywordlist( $keyword_list );
712
713 This method returns a list of keywords, correctly URL escaped and split
714 out of the supplied string
715
716 put() Send output to browser
717
718 CGI.pm alias for print. $q->put('Hello World!') will print the usual
719
720 print() Send output to browser
721
722 CGI.pm alias for print. $q->print('Hello World!') will print the usual
723
725 Netscape browsers versions 1.1 and higher, and all versions of Internet
726 Explorer, support a so-called "cookie" designed to help maintain state
727 within a browser session. CGI.pm has several methods that support
728 cookies.
729
730 A cookie is a name=value pair much like the named parameters in a CGI
731 query string. CGI scripts create one or more cookies and send them to
732 the browser in the HTTP header. The browser maintains a list of cook‐
733 ies that belong to a particular Web server, and returns them to the CGI
734 script during subsequent interactions.
735
736 In addition to the required name=value pair, each cookie has several
737 optional attributes:
738
739 1. an expiration time
740 This is a time/date string (in a special GMT format) that indicates
741 when a cookie expires. The cookie will be saved and returned to
742 your script until this expiration date is reached if the user exits
743 the browser and restarts it. If an expiration date isn't speci‐
744 fied, the cookie will remain active until the user quits the
745 browser.
746
747 2. a domain
748 This is a partial or complete domain name for which the cookie is
749 valid. The browser will return the cookie to any host that matches
750 the partial domain name. For example, if you specify a domain name
751 of ".capricorn.com", then the browser will return the cookie to Web
752 servers running on any of the machines "www.capricorn.com",
753 "www2.capricorn.com", "feckless.capricorn.com", etc. Domain names
754 must contain at least two periods to prevent attempts to match on
755 top level domains like ".edu". If no domain is specified, then the
756 browser will only return the cookie to servers on the host the
757 cookie originated from.
758
759 3. a path
760 If you provide a cookie path attribute, the browser will check it
761 against your script's URL before returning the cookie. For exam‐
762 ple, if you specify the path "/cgi-bin", then the cookie will be
763 returned to each of the scripts "/cgi-bin/tally.pl",
764 "/cgi-bin/order.pl", and "/cgi-bin/customer_service/complain.pl",
765 but not to the script "/cgi-private/site_admin.pl". By default,
766 path is set to "/", which causes the cookie to be sent to any CGI
767 script on your site.
768
769 4. a "secure" flag
770 If the "secure" attribute is set, the cookie will only be sent to
771 your script if the CGI request is occurring on a secure channel,
772 such as SSL.
773
774 cookie() A simple access method to cookies
775
776 The interface to HTTP cookies is the cookie() method:
777
778 $cookie = $q->cookie( -name => 'sessionID',
779 -value => 'xyzzy',
780 -expires => '+1h',
781 -path => '/cgi-bin/database',
782 -domain => '.capricorn.org',
783 -secure => 1
784 );
785 print $q->header(-cookie=>$cookie);
786
787 cookie() creates a new cookie. Its parameters include:
788
789 -name
790 The name of the cookie (required). This can be any string at all.
791 Although browsers limit their cookie names to non-whitespace
792 alphanumeric characters, CGI.pm removes this restriction by escap‐
793 ing and unescaping cookies behind the scenes.
794
795 -value
796 The value of the cookie. This can be any scalar value, array ref‐
797 erence, or even associative array reference. For example, you can
798 store an entire associative array into a cookie this way:
799
800 $cookie=$q->cookie( -name => 'family information',
801 -value => \%childrens_ages );
802
803 -path
804 The optional partial path for which this cookie will be valid, as
805 described above.
806
807 -domain
808 The optional partial domain for which this cookie will be valid, as
809 described above.
810
811 -expires
812 The optional expiration date for this cookie. The format is as
813 described in the section on the header() method:
814
815 "+1h" one hour from now
816
817 -secure
818 If set to true, this cookie will only be used within a secure SSL
819 session.
820
821 The cookie created by cookie() must be incorporated into the HTTP
822 header within the string returned by the header() method:
823
824 print $q->header(-cookie=>$my_cookie);
825
826 To create multiple cookies, give header() an array reference:
827
828 $cookie1 = $q->cookie( -name => 'riddle_name',
829 -value => "The Sphynx's Question"
830 );
831 $cookie2 = $q->cookie( -name => 'answers',
832 -value => \%answers
833 );
834 print $q->header( -cookie => [ $cookie1, $cookie2 ] );
835
836 To retrieve a cookie, request it by name by calling cookie() method
837 without the -value parameter:
838
839 use CGI::Simple;
840 $q = new CGI::Simple;
841 $riddle = $q->cookie('riddle_name');
842 %answers = $q->cookie('answers');
843
844 Cookies created with a single scalar value, such as the "riddle_name"
845 cookie, will be returned in that form. Cookies with array and hash
846 values can also be retrieved.
847
848 The cookie and CGI::Simple namespaces are separate. If you have a
849 parameter named 'answers' and a cookie named 'answers', the values
850 retrieved by param() and cookie() are independent of each other. How‐
851 ever, it's simple to turn a CGI parameter into a cookie, and
852 vice-versa:
853
854 # turn a CGI parameter into a cookie
855 $c = $q->cookie( -name=>'answers', -value=>[$q->param('answers')] );
856 # vice-versa
857 $q->param( -name=>'answers', -value=>[$q->cookie('answers')] );
858
859 raw_cookie()
860
861 Returns the HTTP_COOKIE variable, an HTTP extension implemented by Net‐
862 scape browsers version 1.1 and higher, and all versions of Internet
863 Explorer. Cookies have a special format, and this method call just
864 returns the raw form (?cookie dough). See cookie() for ways of setting
865 and retrieving cooked cookies.
866
867 Called with no parameters, raw_cookie() returns the packed cookie
868 structure. You can separate it into individual cookies by splitting on
869 the character sequence "; ". Called with the name of a cookie,
870 retrieves the unescaped form of the cookie. You can use the regular
871 cookie() method to get the names, or use the raw_fetch() method from
872 the CGI::Simmple::Cookie module.
873
875 Normally the first thing you will do in any CGI script is print out an
876 HTTP header. This tells the browser what type of document to expect,
877 and gives other optional information, such as the language, expiration
878 date, and whether to cache the document. The header can also be manip‐
879 ulated for special purposes, such as server push and pay per view
880 pages.
881
882 header() Create simple or complex HTTP headers
883
884 print $q->header;
885
886 -or-
887
888 print $q->header('image/gif');
889
890 -or-
891
892 print $q->header('text/html','204 No response');
893
894 -or-
895
896 print $q->header( -type => 'image/gif',
897 -nph => 1,
898 -status => '402 Payment required',
899 -expires => '+3d',
900 -cookie => $cookie,
901 -charset => 'utf-7',
902 -attachment => 'foo.gif',
903 -Cost => '$2.00'
904 );
905
906 header() returns the Content-type: header. You can provide your own
907 MIME type if you choose, otherwise it defaults to text/html. An
908 optional second parameter specifies the status code and a human-read‐
909 able message. For example, you can specify 204, "No response" to cre‐
910 ate a script that tells the browser to do nothing at all.
911
912 The last example shows the named argument style for passing arguments
913 to the CGI methods using named parameters. Recognized parameters are
914 -type, -status, -cookie, -target, -expires, -nph, -charset and -attach‐
915 ment. Any other named parameters will be stripped of their initial
916 hyphens and turned into header fields, allowing you to specify any HTTP
917 header you desire.
918
919 For example, you can produce non-standard HTTP header fields by provid‐
920 ing them as named arguments:
921
922 print $q->header( -type => 'text/html',
923 -nph => 1,
924 -cost => 'Three smackers',
925 -annoyance_level => 'high',
926 -complaints_to => 'bit bucket'
927 );
928
929 This will produce the following non-standard HTTP header:
930
931 HTTP/1.0 200 OK
932 Cost: Three smackers
933 Annoyance-level: high
934 Complaints-to: bit bucket
935 Content-type: text/html
936
937 Note that underscores are translated automatically into hyphens. This
938 feature allows you to keep up with the rapidly changing HTTP "stan‐
939 dards".
940
941 The -type is a key element that tell the browser how to display your
942 document. The default is 'text/html'. Common types are:
943
944 text/html
945 text/plain
946 image/gif
947 image/jpg
948 image/png
949 application/octet-stream
950
951 The -status code is the HTTP response code. The default is 200 OK. Com‐
952 mon status codes are:
953
954 200 OK
955 204 No Response
956 301 Moved Permanently
957 302 Found
958 303 See Other
959 307 Temporary Redirect
960 400 Bad Request
961 401 Unauthorized
962 403 Forbidden
963 404 Not Found
964 405 Not Allowed
965 408 Request Timed Out
966 500 Internal Server Error
967 503 Service Unavailable
968 504 Gateway Timed Out
969
970 The -expires parameter lets you indicate to a browser and proxy server
971 how long to cache pages for. When you specify an absolute or relative
972 expiration interval with this parameter, some browsers and proxy
973 servers will cache the script's output until the indicated expiration
974 date. The following forms are all valid for the -expires field:
975
976 +30s 30 seconds from now
977 +10m ten minutes from now
978 +1h one hour from now
979 -1d yesterday (i.e. "ASAP!")
980 now immediately
981 +3M in three months
982 +10y in ten years time
983 Thursday, 25-Apr-1999 00:40:33 GMT at the indicated time & date
984
985 The -cookie parameter generates a header that tells the browser to pro‐
986 vide a "magic cookie" during all subsequent transactions with your
987 script. Netscape cookies have a special format that includes interest‐
988 ing attributes such as expiration time. Use the cookie() method to
989 create and retrieve session cookies.
990
991 The -target is for frames use
992
993 The -nph parameter, if set to a true value, will issue the correct
994 headers to work with a NPH (no-parse-header) script. This is important
995 to use with certain servers that expect all their scripts to be NPH.
996
997 The -charset parameter can be used to control the character set sent to
998 the browser. If not provided, defaults to ISO-8859-1. As a side
999 effect, this sets the charset() method as well.
1000
1001 The -attachment parameter can be used to turn the page into an attach‐
1002 ment. Instead of displaying the page, some browsers will prompt the
1003 user to save it to disk. The value of the argument is the suggested
1004 name for the saved file. In order for this to work, you may have to
1005 set the -type to 'application/octet-stream'.
1006
1007 no_cache() Preventing browser caching of scripts
1008
1009 Most browsers will not cache the output from CGI scripts. Every time
1010 the browser reloads the page, the script is invoked anew. However some
1011 browsers do cache pages. You can discourage this behavior using the
1012 no_cache() function.
1013
1014 $q->no_cache(1); # turn caching off by sending appropriate headers
1015 $q->no_cache(1); # do not send cache related headers.
1016
1017 $q->no_cache(1);
1018 print header (-type=>'image/gif', -nph=>1);
1019
1020 This will produce a header like the following:
1021
1022 HTTP/1.0 200 OK
1023 Server: Apache - accept no substitutes
1024 Expires: Thu, 15 Nov 2001 03:37:50 GMT
1025 Date: Thu, 15 Nov 2001 03:37:50 GMT
1026 Pragma: no-cache
1027 Content-Type: image/gif
1028
1029 Both the Pragma: no-cache header field and an Expires header that cor‐
1030 responds to the current time (ie now) will be sent.
1031
1032 cache() Preventing browser caching of scripts
1033
1034 The somewhat ill named cache() method is a legacy from CGI.pm. It oper‐
1035 ates the same as the new no_cache() method. The difference is/was that
1036 when set it results only in the Pragma: no-cache line being printed.
1037 Expires time data is not sent.
1038
1039 redirect() Generating a redirection header
1040
1041 print $q->redirect('http://somewhere.else/in/movie/land');
1042
1043 Sometimes you don't want to produce a document yourself, but simply re‐
1044 direct the browser elsewhere, perhaps choosing a URL based on the time
1045 of day or the identity of the user.
1046
1047 The redirect() function redirects the browser to a different URL. If
1048 you use redirection like this, you should not print out a header as
1049 well.
1050
1051 One hint I can offer is that relative links may not work correctly when
1052 you generate a redirection to another document on your site. This is
1053 due to a well-intentioned optimization that some servers use. The
1054 solution to this is to use the full URL (including the http: part) of
1055 the document you are redirecting to.
1056
1057 You can also use named arguments:
1058
1059 print $q->redirect( -uri=>'http://somewhere.else/in/movie/land',
1060 -nph=>1
1061 );
1062
1063 The -nph parameter, if set to a true value, will issue the correct
1064 headers to work with a NPH (no-parse-header) script. This is important
1065 to use with certain servers, such as Microsoft ones, which expect all
1066 their scripts to be NPH.
1067
1069 There are a number of pragmas that you can specify in your use
1070 CGI::Simple statement. Pragmas, which are always preceded by a hyphen,
1071 change the way that CGI::Simple functions in various ways. You can gen‐
1072 erally achieve exactly the same results by setting the underlying
1073 $GLOBAL_VARIABLES.
1074
1075 For example the '-upload' pargma will enable file uploads:
1076
1077 use CGI::Simple qw(-upload);
1078
1079 In CGI::Simple::Standard Pragmas, function sets , and individual func‐
1080 tions can all be imported in the same use() line. For example, the
1081 following use statement imports the standard set of functions and
1082 enables debugging mode (pragma -debug):
1083
1084 use CGI::Simple::Standard qw(:standard -debug);
1085
1086 The current list of pragmas is as follows:
1087
1088 -no_undef_params
1089 If a value is not given in the query string, as in the queries
1090 "name1=&name2=" or "name1&name2", by default it will be returned as
1091 an empty string.
1092
1093 If you specify the '-no_undef_params' pragma then CGI::Simple
1094 ignores parameters with no values and they will not appear in the
1095 query object.
1096
1097 -nph
1098 This makes CGI.pm produce a header appropriate for an NPH (no
1099 parsed header) script. You may need to do other things as well to
1100 tell the server that the script is NPH. See the discussion of NPH
1101 scripts below.
1102
1103 -newstyle_urls
1104 Separate the name=value pairs in CGI parameter query strings with
1105 semicolons rather than ampersands. For example:
1106
1107 ?name=fred;age=24;favorite_color=3
1108
1109 Semicolon-delimited query strings are always accepted, but will not
1110 be emitted by self_url() and query_string() unless the -new‐
1111 style_urls pragma is specified.
1112
1113 -oldstyle_urls
1114 Separate the name=value pairs in CGI parameter query strings with
1115 ampersands rather than semicolons. This is the default.
1116
1117 ?name=fred&age=24&favorite_color=3
1118
1119 -autoload
1120 This is only available for CGI::Simple::Standard and uses AUTOLOAD
1121 to load functions on demand. See the CGI::Simple::Standard docs for
1122 details.
1123
1124 -no_debug
1125 This turns off the command-line processing features. This is the
1126 default.
1127
1128 -debug1 and debug2
1129 This turns on debugging. At debug level 1 CGI::Simple will read
1130 arguments from the command-line. At debug level 2 CGI.pm will pro‐
1131 duce the prompt "(offline mode: enter name=value pairs on standard
1132 input)" and wait for input on STDIN. If no number is specified then
1133 a debug level of 2 is used.
1134
1135 See the section on debugging for more details.
1136
1137 -default
1138 This sets the default global values for CGI.pm which will enable
1139 infinite size file uploads, and specify the '-newstyle_urls' and
1140 '-debug1' pragmas
1141
1142 -no_upload
1143 Disable uploads - the default setting
1144
1145 - upload
1146 Enable uploads - the CGI.pm default
1147
1148 -unique_header
1149 Only allows headers to be generated once per script invocation
1150
1151 -carp
1152 Carp when cgi_error() called, default is to do nothing
1153
1154 -croak
1155 Croak when cgi_error() called, default is to do nothing
1156
1158 NPH, or "no-parsed-header", scripts bypass the server completely by
1159 sending the complete HTTP header directly to the browser. This has
1160 slight performance benefits, but is of most use for taking advantage of
1161 HTTP extensions that are not directly supported by your server, such as
1162 server push and PICS headers.
1163
1164 Servers use a variety of conventions for designating CGI scripts as
1165 NPH. Many Unix servers look at the beginning of the script's name for
1166 the prefix "nph-". The Macintosh WebSTAR server and Microsoft's Inter‐
1167 net Information Server, in contrast, try to decide whether a program is
1168 an NPH script by examining the first line of script output.
1169
1170 CGI.pm supports NPH scripts with a special NPH mode. When in this
1171 mode, CGI.pm will output the necessary extra header information when
1172 the header() and redirect() methods are called. You can set NPH mode in
1173 any of the following ways:
1174
1175 In the use statement
1176 Simply add the "-nph" pragma to the use:
1177
1178 use CGI::Simple qw(-nph)
1179
1180 By calling the nph() method:
1181 Call nph() with a non-zero parameter at any point after using
1182 CGI.pm in your program.
1183
1184 $q->nph(1)
1185
1186 By using -nph parameters
1187 in the header() and redirect() statements:
1188
1189 print $q->header(-nph=>1);
1190
1191 The Microsoft Internet Information Server requires NPH mode. CGI::Sim‐
1192 ple will automatically detect when the script is running under IIS and
1193 put itself into this mode. You do not need to do this manually,
1194 although it won't hurt anything if you do. However, note that if you
1195 have applied Service Pack 6, much of the functionality of NPH scripts,
1196 including the ability to redirect while setting a cookie, b<do not work
1197 at all> on IIS without a special patch from Microsoft. See http://sup‐
1198 port.microsoft.com/support/kb/articles/Q280/3/41.ASP: Non-Parsed Head‐
1199 ers Stripped From CGI Applications That Have nph- Prefix in Name.
1200
1202 CGI.pm provides four simple functions for producing multipart documents
1203 of the type needed to implement server push. These functions were gra‐
1204 ciously provided by Ed Jordan <ed@fidalgo.net> with additions from
1205 Andrew Benham <adsb@bigfoot.com>
1206
1207 You are also advised to put the script into NPH mode and to set $⎪ to 1
1208 to avoid buffering problems.
1209
1210 Only Netscape Navigator supports server push. Internet Explorer
1211 browsers do not.
1212
1213 Here is a simple script that demonstrates server push:
1214
1215 #!/usr/local/bin/perl
1216 use CGI::Simple::Standard qw/:push -nph/;
1217 $⎪ = 1;
1218 print multipart_init(-boundary=>'----here we go!');
1219 foreach (0 .. 4) {
1220 print multipart_start(-type=>'text/plain'),
1221 "The current time is ",scalar(localtime),"\n";
1222 if ($_ < 4) {
1223 print multipart_end;
1224 }
1225 else {
1226 print multipart_final;
1227 }
1228 sleep 1;
1229 }
1230
1231 This script initializes server push by calling multipart_init(). It
1232 then enters a loop in which it begins a new multipart section by call‐
1233 ing multipart_start(), prints the current local time, and ends a multi‐
1234 part section with multipart_end(). It then sleeps a second, and begins
1235 again. On the final iteration, it ends the multipart section with mul‐
1236 tipart_final() rather than with multipart_end().
1237
1238 multipart_init() Initialize the multipart system
1239
1240 multipart_init(-boundary=>$boundary);
1241
1242 Initialize the multipart system. The -boundary argument specifies what
1243 MIME boundary string to use to separate parts of the document. If not
1244 provided, CGI.pm chooses a reasonable boundary for you.
1245
1246 multipart_start() Start a new part of the multipart document
1247
1248 multipart_start(-type=>$type)
1249
1250 Start a new part of the multipart document using the specified MIME
1251 type. If not specified, text/html is assumed.
1252
1253 multipart_end() End a multipart part
1254
1255 multipart_end()
1256
1257 End a part. You must remember to call multipart_end() once for each
1258 multipart_start(), except at the end of the last part of the multipart
1259 document when multipart_final() should be called instead of multi‐
1260 part_end().
1261
1262 multipart_final()
1263
1264 multipart_final()
1265
1266 End all parts. You should call multipart_final() rather than multi‐
1267 part_end() at the end of the last part of the multipart document.
1268
1269 CGI::Push
1270
1271 Users interested in server push applications should also have a look at
1272 the CGI::Push module.
1273
1275 If you are running the script from the command line or in the perl
1276 debugger, you can pass the script a list of keywords or parameter=value
1277 pairs on the command line or from standard input (you don't have to
1278 worry about tricking your script into reading from environment vari‐
1279 ables). Before you do this you will need to change the debug level
1280 from the default level of 0 (no debug) to either 1 if you want to debug
1281 from @ARGV (the command line) of 2 if you want to debug from STDIN. You
1282 can do this using the debug pragma like this:
1283
1284 use CGI::Simple qw(-debug2); # set debug to level 2 => from STDIN
1285
1286 or this:
1287
1288 $CGI::Simple::DEBUG = 1; # set debug to level 1 => from @ARGV
1289
1290 At debug level 1 you can pass keywords and name=value pairs like this:
1291
1292 your_script.pl keyword1 keyword2 keyword3
1293
1294 or this:
1295
1296 your_script.pl keyword1+keyword2+keyword3
1297
1298 or this:
1299
1300 your_script.pl name1=value1 name2=value2
1301
1302 or this:
1303
1304 your_script.pl name1=value1&name2=value2
1305
1306 At debug level 2 you can feed newline-delimited name=value pairs to the
1307 script on standard input. You will be presented with the following
1308 prompt:
1309
1310 (offline mode: enter name=value pairs on standard input)
1311
1312 You end the input with your system dependent end of file character.
1313 You should try ^Z ^X ^D and ^C if all else fails. The ^ means hold down
1314 the [Ctrl] button while you press the other key.
1315
1316 When debugging, you can use quotes and backslashes to escape characters
1317 in the familiar shell manner, letting you place spaces and other funny
1318 characters in your parameter=value pairs:
1319
1320 your_script.pl "name1='I am a long value'" "name2=two\ words"
1321
1322 Dump() Dumping the current object details
1323
1324 The Dump() method produces a string consisting of all the query's
1325 object attributes formatted nicely as a nested list. This dump
1326 includes the name/value pairs and a number of other details. This is
1327 useful for debugging purposes:
1328
1329 print $q->Dump
1330
1331 The actual result of this is HTML escaped formatted text wrapped in
1332 <pre> tags so if you send it straight to the browser it produces some‐
1333 thing that looks like:
1334
1335 $VAR1 = bless( {
1336 '.parameters' => [
1337 'name',
1338 'color'
1339 ],
1340 '.globals' => {
1341 'FATAL' => -1,
1342 'DEBUG' => 0,
1343 'NO_NULL' => 1,
1344 'POST_MAX' => 102400,
1345 'USE_CGI_PM_DEFAULTS' => 0,
1346 'HEADERS_ONCE' => 0,
1347 'NPH' => 0,
1348 'DISABLE_UPLOADS' => 1,
1349 'NO_UNDEF_PARAMS' => 0,
1350 'USE_PARAM_SEMICOLONS' => 0
1351 },
1352 '.fieldnames' => {
1353 'color' => '1',
1354 'name' => '1'
1355 },
1356 '.mod_perl' => '',
1357 'color' => [
1358 'red',
1359 'green',
1360 'blue'
1361 ],
1362 'name' => [
1363 'JaPh,'
1364 ]
1365 }, 'CGI::Simple' );
1366
1367 You may recognize this as valid Perl syntax (which it is) and/or the
1368 output from Data::Dumper (also true). This is the actual guts of how
1369 the information is stored in the query object. All the internal params
1370 start with a . char
1371
1372 Alternatively you can dump your object and the current environment
1373 using:
1374
1375 print $q->Dump(\%ENV);
1376
1377 PrintEnv() Dumping the environment
1378
1379 You can get a similar browser friendly dump of the current %ENV hash
1380 using:
1381
1382 print $q->PrintEnv;
1383
1384 This will produce something like (in the browser):
1385
1386 $VAR1 = {
1387 'QUERY_STRING' => 'name=JaPh%2C&color=red&color=green&color=blue',
1388 'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
1389 'REGRESSION_TEST' => 'simple.t.pl',
1390 'VIM' => 'C:\\WINDOWS\\Desktop\\vim',
1391 'HTTP_REFERER' => 'xxx.sex.com',
1392 'HTTP_USER_AGENT' => 'LWP',
1393 'HTTP_ACCEPT' => 'text/html;q=1, image/gif;q=0.42, */*;q=0.001',
1394 'REMOTE_HOST' => 'localhost',
1395 'HTTP_HOST' => 'the.restaurant.at.the.end.of.the.universe',
1396 'GATEWAY_INTERFACE' => 'bleeding edge',
1397 'REMOTE_IDENT' => 'None of your damn business',
1398 'SCRIPT_NAME' => '/cgi-bin/foo.cgi',
1399 'SERVER_NAME' => 'nowhere.com',
1400 'HTTP_COOKIE' => '',
1401 'CONTENT_LENGTH' => '42',
1402 'HTTPS_A' => 'A',
1403 'HTTP_FROM' => 'spammer@nowhere.com',
1404 'HTTPS_B' => 'B',
1405 'SERVER_PROTOCOL' => 'HTTP/1.0',
1406 'PATH_TRANSLATED' => '/usr/local/somewhere/else',
1407 'SERVER_SOFTWARE' => 'Apache - accept no substitutes',
1408 'PATH_INFO' => '/somewhere/else',
1409 'REMOTE_USER' => 'Just another Perl hacker,',
1410 'REMOTE_ADDR' => '127.0.0.1',
1411 'HTTPS' => 'ON',
1412 'DOCUMENT_ROOT' => '/vs/www/foo',
1413 'REQUEST_METHOD' => 'GET',
1414 'REDIRECT_QUERY_STRING' => '',
1415 'AUTH_TYPE' => 'PGP MD5 DES rot13',
1416 'COOKIE' => 'foo=a%20phrase; bar=yes%2C%20a%20phrase&;I%20say;',
1417 'SERVER_PORT' => '8080'
1418 };
1419
1420 cgi_error() Retrieving CGI::Simple error messages
1421
1422 Errors can occur while processing user input, particularly when pro‐
1423 cessing uploaded files. When these errors occur, CGI::Simple will stop
1424 processing and return an empty parameter list. You can test for the
1425 existence and nature of errors using the cgi_error() function. The
1426 error messages are formatted as HTTP status codes. You can either
1427 incorporate the error text into an HTML page, or use it as the value of
1428 the HTTP status:
1429
1430 my $error = $q->cgi_error;
1431 if ($error) {
1432 print $q->header(-status=>$error);
1433 print "<H2>$error</H2>;
1434 exit;
1435 }
1436
1438 version() Get the CGI::Simple version info
1439
1440 $version = $q->version();
1441
1442 The version() method returns the value of $VERSION
1443
1444 nph() Enable/disable NPH (Non Parsed Header) mode
1445
1446 $q->nph(1); # enable NPH mode
1447 $q->nph(0); # disable NPH mode
1448
1449 The nph() method enables and disables NPH headers. See the NPH section.
1450
1451 all_parameters() Get the names/values of all parameters
1452
1453 @all_parameters = $q->all_parameters();
1454
1455 The all_parameters() method is an alias for param()
1456
1457 charset() Get/set the current character set.
1458
1459 $charset = $q->charset(); # get current charset
1460 $q->charset('utf-42'); # set the charset
1461
1462 The charset() method gets the current charset value if no argument is
1463 supplied or sets it if an argument is supplied.
1464
1465 crlf() Get the system specific line ending sequence
1466
1467 $crlf = $q->crlf();
1468
1469 The crlf() method returns the system specific line ending sequence.
1470
1471 globals() Get/set the value of the remaining global variables
1472
1473 $globals = $q->globals('FATAL'); # get the current value of $FATAL
1474 $globals = $q->globals('FATAL', 1 ); # set croak mode on cgi_error()
1475
1476 The globals() method gets/sets the values of the global variables after
1477 the script has been invoked. For globals like $POST_MAX and $DIS‐
1478 ABLE_UPLOADS this makes no difference as they must be set prior to
1479 calling the new constructor but there might be reason the change the
1480 value of others.
1481
1482 auth_type() Get the current authorization/verification method
1483
1484 $auth_type = $q->auth_type();
1485
1486 The auth_type() method returns the value of $ENV{'AUTH_TYPE'} which
1487 should contain the authorization/verification method in use for this
1488 script, if any.
1489
1490 content_length() Get the content length submitted in a POST
1491
1492 $content_length = $q->content_length();
1493
1494 The content_length() method returns the value of $ENV{'AUTH_TYPE'}
1495
1496 content_type() Get the content_type of data submitted in a POST
1497
1498 $content_type = $q->content_type();
1499
1500 The content_type() method returns the content_type of data submitted in
1501 a POST, generally 'multipart/form-data' or 'applica‐
1502 tion/x-www-form-urlencoded' as supplied in $ENV{'CONTENT_TYPE'}
1503
1504 document_root() Get the document root
1505
1506 $document_root = $q->document_root();
1507
1508 The document_root() method returns the value of $ENV{'DOCUMENT_ROOT'}
1509
1510 gateway_interface() Get the gateway interface
1511
1512 $gateway_interface = $q->gateway_interface();
1513
1514 The gateway_interface() method returns the value of $ENV{'GATE‐
1515 WAY_INTERFACE'}
1516
1517 path_translated() Get the value of path translated
1518
1519 $path_translated = $q->path_translated();
1520
1521 The path_translated() method returns the value of $ENV{'PATH_TRANS‐
1522 LATED'}
1523
1524 referer() Spy on your users
1525
1526 $referer = $q->referer();
1527
1528 The referer() method returns the value of $ENV{'REFERER'} This will
1529 return the URL of the page the browser was viewing prior to fetching
1530 your script. Not available for all browsers.
1531
1532 remote_addr() Get the remote address
1533
1534 $remote_addr = $q->remote_addr();
1535
1536 The remote_addr() method returns the value of $ENV{'REMOTE_ADDR'} or
1537 127.0.0.1 (localhost) if this is not defined.
1538
1539 remote_host() Get a value for remote host
1540
1541 $remote_host = $q->remote_host();
1542
1543 The remote_host() method returns the value of $ENV{'REMOTE_HOST'} if it
1544 is defined. If this is not defined it returns $ENV{'REMOTE_ADDR'} If
1545 this is not defined it returns 'localhost'
1546
1547 remote_ident() Get the remote identity
1548
1549 $remote_ident = $q->remote_ident();
1550
1551 The remote_ident() method returns the value of $ENV{'REMOTE_IDENT'}
1552
1553 remote_user() Get the remote user
1554
1555 $remote_user = $q->remote_user();
1556
1557 The remote_user() method returns the authorization/verification name
1558 used for user verification, if this script is protected. The value
1559 comes from $ENV{'REMOTE_USER'}
1560
1561 request_method() Get the request method
1562
1563 $request_method = $q->request_method();
1564
1565 The request_method() method returns the method used to access your
1566 script, usually one of 'POST', 'GET' or 'HEAD' as supplied by
1567 $ENV{'REQUEST_METHOD'}
1568
1569 script_name() Get the script name
1570
1571 $script_name = $q->script_name();
1572
1573 The script_name() method returns the value of $ENV{'SCRIPT_NAME'} if it
1574 is defined. Otherwise it returns Perl's script name from $0. Failing
1575 this it returns a null string ''
1576
1577 server_name() Get the server name
1578
1579 $server_name = $q->server_name();
1580
1581 The server_name() method returns the value of $ENV{'SERVER_NAME'} if
1582 defined or 'localhost' otherwise
1583
1584 server_port() Get the port the server is listening on
1585
1586 $server_port = $q->server_port();
1587
1588 The server_port() method returns the value $ENV{'SERVER_PORT'} if
1589 defined or 80 if not.
1590
1591 server_protocol() Get the current server protocol
1592
1593 $server_protocol = $q->server_protocol();
1594
1595 The server_protocol() method returns the value of $ENV{'SERVER_PROTO‐
1596 COL'} if defined or 'HTTP/1.0' otherwise
1597
1598 server_software() Get the server software
1599
1600 $server_software = $q->server_software();
1601
1602 The server_software() method returns the value $ENV{'SERVER_SOFTWARE'}
1603 or 'cmdline' If the server software is IIS it formats your hard drive,
1604 installs Linux, FTPs to www.apache.org, installs Apache, and then
1605 restores your system from tape. Well maybe not, but it's a nice
1606 thought.
1607
1608 user_name() Get a value for the user name.
1609
1610 $user_name = $q->user_name();
1611
1612 Attempt to obtain the remote user's name, using a variety of different
1613 techniques. This only works with older browsers such as Mosaic. Newer
1614 browsers do not report the user name for privacy reasons!
1615
1616 Technically the user_name() method returns the value of
1617 $ENV{'HTTP_FROM'} or failing that $ENV{'REMOTE_IDENT'} or as a last
1618 choice $ENV{'REMOTE_USER'}
1619
1620 user_agent() Get the users browser type
1621
1622 $ua = $q->user_agent(); # return the user agent
1623 $ok = $q->user_agent('mozilla'); # return true if user agent 'mozilla'
1624
1625 The user_agent() method returns the value of $ENV{'HTTP_USER_AGENT'}
1626 when called without an argument or true or false if the
1627 $ENV{'HTTP_USER_AGENT'} matches the passed argument. The matching is
1628 case insensitive and partial.
1629
1630 virtual_host() Get the virtual host
1631
1632 $virtual_host = $q->virtual_host();
1633
1634 The virtual_host() method returns the value of $ENV{'HTTP_HOST'} if
1635 defined or $ENV{'SERVER_NAME'} as a default. Port numbers are removed.
1636
1637 path_info() Get any extra path info set to the script
1638
1639 $path_info = $q->path_info();
1640
1641 The path_info() method returns additional path information from the
1642 script URL. E.G. fetching /cgi-bin/your_script/additional/stuff will
1643 result in $q->path_info() returning "/additional/stuff".
1644
1645 NOTE: The Microsoft Internet Information Server is broken with respect
1646 to additional path information. If you use the Perl DLL library, the
1647 IIS server will attempt to execute the additional path information as a
1648 Perl script. If you use the ordinary file associations mapping, the
1649 path information will be present in the environment, but incorrect.
1650 The best thing to do is to avoid using additional path information in
1651 CGI scripts destined for use with IIS.
1652
1653 Accept() Get the browser MIME types
1654
1655 $Accept = $q->Accept();
1656
1657 The Accept() method returns a list of MIME types that the remote
1658 browser accepts. If you give this method a single argument correspond‐
1659 ing to a MIME type, as in $q->Accept('text/html'), it will return a
1660 floating point value corresponding to the browser's preference for this
1661 type from 0.0 (don't want) to 1.0. Glob types (e.g. text/*) in the
1662 browser's accept list are handled correctly.
1663
1664 accept() Alias for Accept()
1665
1666 $accept = $q->accept();
1667
1668 The accept() Method is an alias for Accept()
1669
1670 http() Get a range of HTTP related information
1671
1672 $http = $q->http();
1673
1674 Called with no arguments the http() method returns the list of HTTP or
1675 HTTPS environment variables, including such things as HTTP_USER_AGENT,
1676 HTTP_ACCEPT_LANGUAGE, and HTTP_ACCEPT_CHARSET, corresponding to the
1677 like-named HTTP header fields in the request. Called with the name of
1678 an HTTP header field, returns its value. Capitalization and the use of
1679 hyphens versus underscores are not significant.
1680
1681 For example, all three of these examples are equivalent:
1682
1683 $requested_language = $q->http('Accept-language');
1684 $requested_language = $q->http('Accept_language');
1685 $requested_language = $q->http('HTTP_ACCEPT_LANGUAGE');
1686
1687 https() Get a range of HTTPS related information
1688
1689 $https = $q->https();
1690
1691 The https() method is similar to the http() method except that when
1692 called without an argument it returns the value of $ENV{'HTTPS'} which
1693 will be true if a HTTPS connection is in use and false otherwise.
1694
1695 protocol() Get the current protocol
1696
1697 $protocol = $q->protocol();
1698
1699 The protocol() method returns 'https' if a HTTPS connection is in use
1700 or the server_protocol() minus version numbers ('http') otherwise.
1701
1702 url() Return the script's URL in several formats
1703
1704 $full_url = $q->url();
1705 $full_url = $q->url(-full=>1);
1706 $relative_url = $q->url(-relative=>1);
1707 $absolute_url = $q->url(-absolute=>1);
1708 $url_with_path = $q->url(-path_info=>1);
1709 $url_with_path_and_query = $q->url(-path_info=>1,-query=>1);
1710 $netloc = $q->url(-base => 1);
1711
1712 url() returns the script's URL in a variety of formats. Called without
1713 any arguments, it returns the full form of the URL, including host name
1714 and port number
1715
1716 http://your.host.com/path/to/script.cgi
1717
1718 You can modify this format with the following named arguments:
1719
1720 -absolute
1721 If true, produce an absolute URL, e.g.
1722
1723 /path/to/script.cgi
1724
1725 -relative
1726 Produce a relative URL. This is useful if you want to reinvoke
1727 your script with different parameters. For example:
1728
1729 script.cgi
1730
1731 -full
1732 Produce the full URL, exactly as if called without any arguments.
1733 This overrides the -relative and -absolute arguments.
1734
1735 -path (-path_info)
1736 Append the additional path information to the URL. This can be
1737 combined with -full, -absolute or -relative. -path_info is pro‐
1738 vided as a synonym.
1739
1740 -query (-query_string)
1741 Append the query string to the URL. This can be combined with
1742 -full, -absolute or -relative. -query_string is provided as a syn‐
1743 onym.
1744
1745 -base
1746 Generate just the protocol and net location, as in
1747 http://www.foo.com:8000
1748
1749 self_url() Get the scripts complete URL
1750
1751 $self_url = $q->self_url();
1752
1753 The self_url() method returns the value of:
1754
1755 $self->url( '-path_info'=>1, '-query'=>1, '-full'=>1 );
1756
1757 state() Alias for self_url()
1758
1759 $state = $q->state();
1760
1761 The state() method is an alias for self_url()
1762
1764 To make it easier to port existing programs that use cgi-lib.pl all the
1765 subs within cgi-lib.pl are available in CGI::Simple. Using the func‐
1766 tional interface of CGI::Simple::Standard porting is as easy as:
1767
1768 OLD VERSION
1769 require "cgi-lib.pl";
1770 &ReadParse;
1771 print "The value of the antique is $in{'antique'}.\n";
1772
1773 NEW VERSION
1774 use CGI::Simple::Standard qw(:cgi-lib);
1775 &ReadParse;
1776 print "The value of the antique is $in{'antique'}.\n";
1777
1778 CGI:Simple's ReadParse() routine creates a variable named %in, which
1779 can be accessed to obtain the query variables. Like ReadParse, you can
1780 also provide your own variable via a glob. Infrequently used features
1781 of ReadParse(), such as the creation of @in and $in variables, are not
1782 supported.
1783
1784 You can also use the OO interface of CGI::Simple and call ReadParse()
1785 and other cgi-lib.pl functions like this:
1786
1787 &CGI::Simple::ReadParse; # get hash values in %in
1788
1789 my $q = new CGI::Simple;
1790 $q->ReadParse(); # same thing
1791
1792 CGI::Simple::ReadParse(*field); # get hash values in %field function style
1793
1794 my $q = new CGI::Simple;
1795 $q->ReadParse(*field); # same thing
1796
1797 Once you use ReadParse() under the functional interface , you can
1798 retrieve the query object itself this way if needed:
1799
1800 $q = $in{'CGI'};
1801
1802 Either way it allows you to start using the more interesting features
1803 of CGI.pm without rewriting your old scripts from scratch.
1804
1805 Unlike CGI.pm all the cgi-lib.pl functions from Version 2.18 are sup‐
1806 ported:
1807
1808 ReadParse()
1809 SplitParam()
1810 MethGet()
1811 MethPost()
1812 MyBaseUrl()
1813 MyURL()
1814 MyFullUrl()
1815 PrintHeader()
1816 HtmlTop()
1817 HtmlBot()
1818 PrintVariables()
1819 PrintEnv()
1820 CgiDie()
1821 CgiError()
1822
1824 This module uses Selfloader and the __DATA__ token to ensure that only
1825 code that is used gets complied. This optimises performance but means
1826 that it will not work under mod_perl in its default configuration. To
1827 configure it to run under mod perl you would need to remove two lines
1828 from the module.
1829
1830 use Selfloader;
1831
1832 ....
1833
1834 __DATA__
1835
1836 With these two lines gone the entire module will load and compile at
1837 mod_perl startup. CGI::Simple's pure OO methods return data signifi‐
1838 cantly faster than CGI.pm's OO methods
1839
1841 I has long been suggested that the CGI and HTML parts of CGI.pm should
1842 be split into separate modules (even the author suggests this!),
1843 CGI::Simple represents the realization of this and contains the com‐
1844 plete CGI side of CGI.pm. Code-wise it weighs in at a little under 30%
1845 of the size of CGI.pm at a little under 1000 lines. It uses SelfLoader
1846 and only compiles the first 350 lines. Other routines are loaded on
1847 first use. Internally around half the code is new although the method
1848 interfaces remain unchanged.
1849
1850 A great deal of care has been taken to ensure that the interface
1851 remains unchanged although a few tweaks have been made. The test suite
1852 is extensive and includes all the CGI.pm test scripts as well as a
1853 series of new test scripts. You may like to have a look at /t/concur.t
1854 which makes 160 tests of CGI::Simple and CGI in parallel and compares
1855 the results to ensure they are identical. This is the case as of CGI.pm
1856 2.78.
1857
1858 You can't make an omelet without breaking eggs. A large number of meth‐
1859 ods and global variables have been deleted as detailed below. Some
1860 pragmas are also gone. In the tarball there is a script /misc/check.pl
1861 that will check if a script seems to be using any of these now non
1862 existent methods, globals or pragmas. You call it like this:
1863
1864 perl check.pl <files>
1865
1866 If it finds any likely candidates it will print a line with the line
1867 number, problem method/global and the complete line. For example here
1868 is some output from running the script on CGI.pm:
1869
1870 ...
1871 3162: Problem:'$CGI::OS' local($CRLF) = "\015\012" if $CGI::OS eq 'VMS';
1872 3165: Problem:'fillBuffer' $self->fillBuffer($FILLUNIT);
1873 ....
1874
1876 CGI::Simple is strict and warnings compliant. SelfLoader is used to
1877 load only the required code. You can easily optimize code loading sim‐
1878 ply by moving the __DATA__ token. Commonly called methods should go
1879 above the token and will be compiled at compile time (on load). Uncom‐
1880 monly used methods go below the __DATA__ token and will only be com‐
1881 piled as required at runtime when the method is actually called.
1882
1883 As well as using SelfLoader to load the non core methods, Simple.pm
1884 uses IO::File to supply anonymous temp files for file uploads and
1885 Data::Dumper for cloning objects and dumping data. These modules are
1886 all part of the standard Perl distribution.
1887
1888 There are 4 modules in this distribution:
1889
1890 CGI/Simple.pm supplies all the core code.
1891 CGI/Simple/Cookie.pm supplies the cookie handling functions.
1892 CGI/Simple/Util.pm supplies a variety of utility functions
1893 CGI/Simple/Standard.pm supplies a functional interface for Simple.pm
1894
1895 Simple.pm is the core module that provide all the essential functional‐
1896 ity. Cookie.pm is a shortened rehash of the CGI.pm module of the same
1897 name which supplies the required cookie functionality. Util.pm has been
1898 recoded to use an internal object for data storage and supplies rarely
1899 needed non core functions and/or functions needed for the HTML side of
1900 things. Standard.pm is a wrapper module that supplies a complete func‐
1901 tional interface to the OO back end supplied by CGI::Simple.
1902
1903 Although a serious attempt has been made to keep the interface identi‐
1904 cal, some minor changes and tweaks have been made. They will likely be
1905 insignificant to most users but here are the gory details.
1906
1907 Globals Variables
1908
1909 The list of global variables has been pruned by 75%. Here is the com‐
1910 plete list of the global variables used:
1911
1912 $VERSION = "0.01";
1913 # set this to 1 to use CGI.pm default global settings
1914 $USE_CGI_PM_DEFAULTS = 0 unless defined $USE_CGI_PM_DEFAULTS;
1915 # see if user wants old CGI.pm defaults
1916 do{ _use_cgi_pm_global_settings(); return } if $USE_CGI_PM_DEFAULTS;
1917 # no file uploads by default, set to 0 to enable uploads
1918 $DISABLE_UPLOADS = 1 unless defined $DISABLE_UPLOADS;
1919 # use a post max of 100K, set to -1 for no limits
1920 $POST_MAX = 102_400 unless defined $POST_MAX;
1921 # do not include undefined params parsed from query string
1922 $NO_UNDEF_PARAMS = 0 unless defined $NO_UNDEF_PARAMS;
1923 # separate the name=value pairs with ; rather than &
1924 $USE_PARAM_SEMICOLONS = 0 unless defined $USE_PARAM_SEMICOLONS;
1925 # only print headers once
1926 $HEADERS_ONCE = 0 unless defined $HEADERS_ONCE;
1927 # Set this to 1 to enable NPH scripts
1928 $NPH = 0 unless defined $NPH;
1929 # 0 => no debug, 1 => from @ARGV, 2 => from STDIN
1930 $DEBUG = 0 unless defined $DEBUG;
1931 # filter out null bytes in param - value pairs
1932 $NO_NULL = 1 unless defined $NO_NULL;
1933 # set behavior when cgi_err() called -1 => silent, 0 => carp, 1 => croak
1934 $FATAL = -1 unless defined $FATAL;
1935
1936 Four of the default values of the old CGI.pm variables have been
1937 changed. Unlike CGI.pm which by default allows unlimited POST data and
1938 file uploads by default CGI::Simple limits POST data size to 100kB and
1939 denies file uploads by default. $USE_PARAM_SEMICOLONS is set to 0 by
1940 default so we use (old style) & rather than ; as the pair separator for
1941 query strings. Debugging is disabled by default.
1942
1943 There are three new global variables. If $NO_NULL is true (the default)
1944 then CGI::Simple will strip null bytes out of names, values and key‐
1945 words. Null bytes can do interesting things to C based code like Perl.
1946 Uploaded files are not touched. $FATAL controls the behavior when
1947 cgi_error() is called. The default value of -1 makes errors silent.
1948 $USE_CGI_PM_DEFAULTS reverts the defaults to the CGI.pm standard values
1949 ie unlimited file uploads via POST for DNS attacks. You can also get
1950 the defaults back by using the '-default' pragma in the use:
1951
1952 use CGI::Simple qw(-default);
1953 use CGI::Simple::Standard qw(-default);
1954
1955 The values of the global variables are stored in the CGI::Simple object
1956 and can be referenced and changed using the globals() method like this:
1957
1958 my $value = $q->globals( 'VARNAME' ); # get
1959 $q->globals( 'VARNAME', 'some value' ); # set
1960
1961 As with many CGI.pm methods if you pass the optional value that will be
1962 set.
1963
1964 The $CGI::Simple::VARNAME = 'N' syntax is only useful prior to calling
1965 the new() constructor. After that all reference is to the values stored
1966 in the CGI::Simple object so you must change these using the globals()
1967 method.
1968
1969 $DISABLE_UPLOADS and $POST_MAX *must* be set prior to calling the con‐
1970 structor if you want the changes to have any effect as they control
1971 behavior during initialization. This is the same a CGI.pm although some
1972 people seem to miss this rather important point and set these after
1973 calling the constructor which does nothing.
1974
1975 The following globals are no longer relevant and have all been deleted:
1976
1977 $AUTOLOADED_ROUTINES
1978 $AUTOLOAD_DEBUG
1979 $BEEN_THERE
1980 $CRLF
1981 $DEFAULT_DTD
1982 $EBCDIC
1983 $FH
1984 $FILLUNIT
1985 $IIS
1986 $IN
1987 $INITIAL_FILLUNIT
1988 $JSCRIPT
1989 $MAC
1990 $MAXTRIES
1991 $MOD_PERL
1992 $NOSTICKY
1993 $OS
1994 $PERLEX
1995 $PRIVATE_TEMPFILES
1996 $Q
1997 $QUERY_CHARSET
1998 $QUERY_PARAM
1999 $SCRATCH
2000 $SL
2001 $SPIN_LOOP_MAX
2002 $TIMEOUT
2003 $TMPDIRECTORY
2004 $XHTML
2005 %EXPORT
2006 %EXPORT_OK
2007 %EXPORT_TAGS
2008 %OVERLOAD
2009 %QUERY_FIELDNAMES
2010 %SUBS
2011 @QUERY_PARAM
2012 @TEMP
2013
2014 Notes: CGI::Simple uses IO::File->new_tmpfile to get tempfile filehan‐
2015 dles. These are private by default so $PRIVATE_TEMPFILES is no longer
2016 required nor is $TMPDIRECTORY. The value that were stored in $OS,
2017 $CRLF, $QUERY_CHARSET and $EBCDIC are now stored in the CGI::Sim‐
2018 ple::Util object where they find most of their use. The $MOD_PERL and
2019 $PERLEX values are now stored in our CGI::Simple object. $IIS was only
2020 used once in path_info(). $SL the system specific / \ : path delimiter
2021 is not required as we let IO::File handle our tempfile requirements.
2022 The rest of the globals are HTML related, export related, hand rolled
2023 autoload related or serve obscure purposes in CGI.pm
2024
2025 Changes to pragmas
2026
2027 There are some new pragmas available. See the pragmas section for
2028 details. The following CGI.pm pragmas are not available:
2029
2030 -any
2031 -compile
2032 -nosticky
2033 -no_xhtml
2034 -private_tempfiles
2035
2036 -compile has been removed as it is not available using SelfLoader. If
2037 you wish to compile all of CGI::Simple comment out the line:
2038
2039 use SelfLoader
2040
2041 and remove the __DATA__ token. Tempfiles are now private by default and
2042 the other pragmas are HTML related.
2043
2044 Filehandles
2045
2046 Unlike CGI.pm which tries to accept all filehandle like objects only
2047 \*FH and $fh are accepted by CGI::Simple as file accessors for new()
2048 and save(). IO::File objects work fine.
2049
2050 Hash interface
2051
2052 %hash = $q->Vars(); # pack values with "\0";
2053 %hash = $q->Vars(","); # comma separate values
2054
2055 You may optionally pass Vars() a string that will be used to separate
2056 multiple values when they are packed into the single hash value. If no
2057 value is supplied the default "\0" (null byte) will be used. Null bytes
2058 are dangerous things for C based code (ie Perl).
2059
2060 cgi-lib.pl
2061
2062 All the cgi-lib.pl 2.18 routines are supported. Unlike CGI.pm all the
2063 subroutines from cgi-lib.pl are included. They have been GOLFED down to
2064 25 lines but they all work pretty much the same as the originals.
2065
2067 Here is a complete list of all the CGI::Simple methods.
2068
2069 Guts (hands off, except of course for new)
2070
2071 _initialize_globals
2072 _use_cgi_pm_global_settings
2073 _store_globals
2074 import
2075 _reset_globals
2076 new
2077 DESTROY
2078 _initialize
2079 _read_parse
2080 _parse_params
2081 _add_param
2082 _parse_keywordlist
2083 _parse_multipart
2084 _save_tmpfile
2085 _read_data
2086
2087 Core Methods
2088
2089 param
2090 add_param
2091 param_fetch
2092 url_param
2093 keywords
2094 Vars
2095 append
2096 delete
2097 Delete
2098 delete_all
2099 Delete_all
2100 upload
2101 upload_info
2102 query_string
2103 parse_query_string
2104 parse_keywordlist
2105
2106 Save and Restore from File Methods
2107
2108 _init_from_file
2109 save
2110 save_parameters
2111
2112 Miscellaneous Methods
2113
2114 url_decode
2115 url_encode
2116 escapeHTML
2117 unescapeHTML
2118 put
2119 print
2120
2121 Cookie Methods
2122
2123 cookie
2124 raw_cookie
2125
2126 Header Methods
2127
2128 header
2129 cache
2130 no_cache
2131 redirect
2132
2133 Server Push Methods
2134
2135 multipart_init
2136 multipart_start
2137 multipart_end
2138 multipart_final
2139
2140 Debugging Methods
2141
2142 read_from_cmdline
2143 Dump
2144 as_string
2145 cgi_error
2146
2147 cgi-lib.pl Compatibility Routines - all 2.18 functions available
2148
2149 _shift_if_ref
2150 ReadParse
2151 SplitParam
2152 MethGet
2153 MethPost
2154 MyBaseUrl
2155 MyURL
2156 MyFullUrl
2157 PrintHeader
2158 HtmlTop
2159 HtmlBot
2160 PrintVariables
2161 PrintEnv
2162 CgiDie
2163 CgiError
2164
2165 Accessor Methods
2166
2167 version
2168 nph
2169 all_parameters
2170 charset
2171 crlf # new, returns OS specific CRLF sequence
2172 globals # get/set global variables
2173 auth_type
2174 content_length
2175 content_type
2176 document_root
2177 gateway_interface
2178 path_translated
2179 referer
2180 remote_addr
2181 remote_host
2182 remote_ident
2183 remote_user
2184 request_method
2185 script_name
2186 server_name
2187 server_port
2188 server_protocol
2189 server_software
2190 user_name
2191 user_agent
2192 virtual_host
2193 path_info
2194 Accept
2195 accept
2196 http
2197 https
2198 protocol
2199 url
2200 self_url
2201 state
2202
2204 There are a few new methods in CGI::Simple as listed below. The high‐
2205 lights are the parse_query_string() method to add the QUERY_STRING data
2206 to your object if the method was POST. The no_cache() method adds an
2207 expires now directive and the Pragma: no-cache directive to the header
2208 to encourage some browsers to do the right thing. PrintEnv() from the
2209 cgi-lib.pl routines will dump an HTML friendly list of the %ENV and
2210 makes a handy addition to Dump() for use in debugging. The upload
2211 method now accepts a filepath as an optional second argument as shown
2212 in the synopsis. If this is supplied the uploaded file will be written
2213 to there automagically.
2214
2215 Internal Routines
2216
2217 _initialize_globals()
2218 _use_cgi_pm_global_settings()
2219 _store_globals()
2220 _initialize()
2221 _init_from_file()
2222 _read_parse()
2223 _parse_params()
2224 _add_param()
2225 _parse_keywordlist()
2226 _parse_multipart()
2227 _save_tmpfile()
2228 _read_data()
2229
2230 New Public Methods
2231
2232 add_param() # adds a param/value(s) pair +/- overwrite
2233 upload_info() # uploaded files MIME type and size
2234 url_decode() # decode s url encoded string
2235 url_encode() # url encode a string
2236 parse_query_string() # add QUERY_STRING data to $q object if 'POST'
2237 no_cache() # add both the Pragma: no-cache
2238 # and Expires/Date => 'now' to header
2239
2240 cgi-lib.pl methods added for completeness
2241
2242 _shift_if_ref() # internal hack reminiscent of self_or_default :-)
2243 MyBaseUrl()
2244 MyURL()
2245 MyFullUrl()
2246 PrintVariables()
2247 PrintEnv()
2248 CgiDie()
2249 CgiError()
2250
2251 New Accessors
2252
2253 crlf() # returns CRLF sequence
2254 globals() # global vars now stored in $q object - get/set
2255 content_length() # returns $ENV{'CONTENT_LENGTH'}
2256 document_root() # returns $ENV{'DOCUMENT_ROOT'}
2257 gateway_interface() # returns $ENV{'GATEWAY_INTERFACE'}
2258
2260 Here is a complete list of what is not included in CGI::Simple. Basi‐
2261 cally all the HTML related stuff plus large redundant chunks of the
2262 guts. The check.pl script in the /misc dir will check to see if a
2263 script is using any of these.
2264
2265 Guts - rearranged, recoded, renamed and hacked out of existence
2266
2267 initialize_globals()
2268 compile()
2269 expand_tags()
2270 self_or_default()
2271 self_or_CGI()
2272 init()
2273 to_filehandle()
2274 save_request()
2275 parse_params()
2276 add_parameter()
2277 binmode()
2278 _make_tag_func()
2279 AUTOLOAD()
2280 _compile()
2281 _setup_symbols()
2282 new_MultipartBuffer()
2283 read_from_client()
2284 import_names() # I dislike this and left it out, so shoot me.
2285
2286 HTML Related
2287
2288 autoEscape()
2289 URL_ENCODED()
2290 MULTIPART()
2291 SERVER_PUSH()
2292 start_html()
2293 _style()
2294 _script()
2295 end_html()
2296 isindex()
2297 startform()
2298 start_form()
2299 end_multipart_form()
2300 start_multipart_form()
2301 endform()
2302 end_form()
2303 _textfield()
2304 textfield()
2305 filefield()
2306 password_field()
2307 textarea()
2308 button()
2309 submit()
2310 reset()
2311 defaults()
2312 comment()
2313 checkbox()
2314 checkbox_group()
2315 _tableize()
2316 radio_group()
2317 popup_menu()
2318 scrolling_list()
2319 hidden()
2320 image_button()
2321 nosticky()
2322 default_dtd()
2323
2324 Upload Related
2325
2326 CGI::Simple uses anonymous tempfiles supplied by IO::File to spool
2327 uploaded files to.
2328
2329 private_tempfiles() # automatic in CGI::Simple
2330 tmpFileName() # all upload files are anonymous
2331 uploadInfo() # relied on FH access, replaced with upload_info()
2332
2333 Really Private Subs (marked as so)
2334
2335 previous_or_default()
2336 register_parameter()
2337 get_fields()
2338 _set_values_and_labels()
2339 _compile_all()
2340 asString()
2341 compare()
2342
2343 Internal Multipart Parsing Routines
2344
2345 read_multipart()
2346 readHeader()
2347 readBody()
2348 read()
2349 fillBuffer()
2350 eof()
2351
2353 Nothing.
2354
2356 As this is 0.01 there are almost bound to be some. Not recommended for
2357 production use.
2358
2360 Copyright 2001 Dr James Freeman <jfreeman@tassie.net.au>
2361
2362 This package is free software and is provided "as is" without express
2363 or implied warranty. It may be used, redistributed and/or modified
2364 under the terms of the Perl Artistic License (see
2365 http://www.perl.com/perl/misc/Artistic.html)
2366
2367 Address bug reports and comments to: jfreeman@tassie.net.au. When
2368 sending bug reports, please provide the version of CGI::Simple, the
2369 version of Perl, the name and version of your Web server, and the name
2370 and version of the operating system you are using. If the problem is
2371 even remotely browser dependent, please provide information about the
2372 affected browsers as well.
2373
2375 Lincoln D. Stein (lstein@cshl.org) and everyone else who worked on the
2376 original CGI.pm upon which this module is heavily based
2377
2378 Brandon Black for some heavy duty testing and bug fixes
2379
2380 John D Robinson and Jeroen Latour for helping solve some interesting
2381 test failures as well as Perlmonks: tommyw, grinder, Jaap, vek, erasei,
2382 jlongino and strider_corinth
2383
2385 CGI, CGI::Simple::Standard, CGI::Simple::Cookie, CGI::Simple::Util
2386
2387
2388
2389perl v5.8.8 2004-11-22 Simple(3)