forked from leejo/CGI.pm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cgi_docs.html
6067 lines (5135 loc) · 221 KB
/
cgi_docs.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML> <HEAD>
<!-- $Id -->
<TITLE>CGI.pm - a Perl5 CGI Library</TITLE>
</HEAD>
<BODY bgcolor="#FFFFFF">
<H1><IMG SRC="examples/dna.small.gif" ALT="[logo]">
CGI.pm - a Perl5 CGI Library</H1>
<p>
<h1>AS OF 10 FEBRUARY 2005 (CGI.pm VERSION 3.06) THIS DOCUMENT IS NO
LONGER BEING MAINTAINED. PLEASE CONSULT THE CGI POD DOCUMENTATION
USING "perldoc CGI"</h1>
<H2>Abstract</H2> This perl 5 library uses objects to create Web
fill-out forms on the fly and to parse their contents. It provides a
simple interface for parsing and interpreting query strings passed to
CGI scripts. However, it also offers a rich set of functions for
creating fill-out forms. Instead of remembering the syntax for HTML
form elements, you just make a series of perl function calls. An
important fringe benefit of this is that the value of the previous
query is used to initialize the form, so that the state of the form is
preserved from invocation to invocation.
<P>Everything is done through a ``CGI'' object. When you create one
of these objects it examines the environment for a query string,
parses it, and stores the results. You can then ask the CGI object to
return or modify the query values. CGI objects handle POST and GET
methods correctly, and correctly distinguish between scripts called
from <ISINDEX> documents and form-based documents. In fact you
can debug your script from the command line without worrying about
setting up environment variables.
<P>A script to create a fill-out form that remembers its state each
time it's invoked is very easy to write with CGI.pm:
<PRE>
#!/usr/local/bin/perl
use CGI qw(:standard);
print header;
print start_html('A Simple Example'),
h1('A Simple Example'),
start_form,
"What's your name? ",textfield('name'),
p,
"What's the combination?",
p,
checkbox_group(-name=>'words',
-values=>['eenie','meenie','minie','moe'],
-defaults=>['eenie','minie']),
p,
"What's your favorite color? ",
popup_menu(-name=>'color',
-values=>['red','green','blue','chartreuse']),
p,
submit,
end_form,
hr;
if (param()) {
print
"Your name is",em(param('name')),
p,
"The keywords are: ",em(join(", ",param('words'))),
p,
"Your favorite color is ",em(param('color')),
hr;
}
print end_html;
</PRE>
<A HREF="examples/tryit.cgi">Select this link to try the script</A>
<BR>
<A HREF="examples/">More scripting examples</A>
<BR>
<a href="http://www.wiley.com/compbooks/stein/source.html">Source code
examples from <cite>The Official Guide to CGI.pm</cite></a>
<p>
<H2><A NAME="contents">Contents</A></H2>
<MENU>
<LI><A HREF="#download">Downloading</A>
<LI><A HREF="#installation">Installation</A>
<LI><a href="#functionvsoo">Function-Oriented vs Object-Oriented Use</a>
<LI><A HREF="#query">Creating a new CGI query object</A>
<LI><A HREF="#saving">Saving the state of the form</A>
<LI><A HREF="#named_param">CGI Functions that Take Multiple Arguments</A>
<LI><A HREF="#header">Creating the HTTP header</A>
<LI><A HREF="#html">HTML shortcuts</A>
<LI><A HREF="#forms">Creating forms</A>
<LI><A HREF="#import">Importing CGI methods</A>
<LI><A HREF="#errors">Retrieving CGI.pm errors</A>
<LI><A HREF="#debugging">Debugging</A>
<LI><A HREF="#environment">HTTP session variables</A>
<LI><A HREF="#cookies">HTTP Cookies</A>
<li><a href="#frames">Support for frames</a>
<li><a href="#javascripting">Support for JavaScript</a>
<li><a href="#stylesheets">Limited Support for Cascading Style Sheets</a>
<LI><A HREF="#nph">Using NPH Scripts</A>
<LI><A HREF="#advanced">Advanced techniques</A>
<LI><A HREF="#subclassing">Subclassing CGI.pm</A>
<LI><A HREF="#mod_perl">Using CGI.pm with mod_perl and FastCGI</A>
<LI><A HREF="#migrating">Migrating from cgi-lib.pl</A>
<LI><a href="#upload_caveats">Using the File Upload Feature</a>
<LI><a href="#push">Server Push</a>
<LI><A HREF="#dos">Avoiding Denial of Service Attacks</A>
<LI><A HREF="#non_unix">Using CGI.pm on non-Unix Platforms</A>
<LI><A HREF="#future">The Relationship of CGI.pm to the CGI::* Modules</A>
<LI><A HREF="#distribution">Distribution information</A>
<LI><A HREF="#book">The CGI.pm Book</A>
<LI><A HREF="#y2000">CGI.pm and the Year 2000 Problem</A>
<LI><A HREF="#bugs">Bug Reporting and Support</A>
<LI><A HREF="#new">What's new?</A>
</MENU>
<HR>
<h2><a name="download">Downloads</a></h2>
<ul>
<li><STRONG><A HREF="CGI.pm.tar.gz">Download gzip tar archive (Unix)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.zip">Download pkzip archive (Windows)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.sit">Download sit archive (Macintosh)</A></STRONG>
<li><strong><A HREF="CGI.pm">Download just the CGI module (uncompressed)</a></strong>
<li><strong><a href="old">Archive of Old Versions</a></strong>
</ul>
<p>
<H2><A NAME="installation">Installation</A></H2>
<ul>
<li><STRONG><A HREF="CGI.pm.tar.gz">Download gzip tar archive (Unix)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.zip">Download pkzip archive (Windows)</A></STRONG>
<li><STRONG><A HREF="CGI.pm.sit">Download sit archive (Macintosh)</A></STRONG>
<li><strong><A HREF="CGI.pm">Download just the CGI module (uncompressed)</a></strong>
</ul>
<p>
The current version of the software can always be downloaded from the
master copy of this document maintained at <a
href="http://stein.cshl.org/WWW/software/CGI/">http://stein.cshl.org/WWW/software/CGI/</a>.
<P>
This package requires perl 5.004 or higher. Earlier versions of Perl
may work, but CGI.pm has not been tested with them. If you're really
stuck, edit the source code to remove the line that says "require
5.004", but don't be surprised if you run into problems.
<p>
If you are using a Unix system, you should have perl do the
installation for you. Move to the directory containing CGI.pm and
type the following commands:
<PRE>
% perl Makefile.PL
% make
% make install
</PRE>
You may need to be root to do the last step.
<p>
This will create two new files in your Perl library. <b>CGI.pm</b> is the
main library file. <b>Carp.pm</b> (in the subdirectory "CGI") contains
some optional utility
routines for writing nicely formatted error messages into your
server logs. See the Carp.pm man page for more details.
<p>
<strong>If you get error messages when you try to install</strong>,
then you are either:
<ol>
<li> Running a Windows NT or Macintosh port of Perl that
doesn't have make or the MakeMaker program built into it.
<li> Have an old version of Perl. Upgrade to 5.004 or higher.
</ol>
In the former case don't panic. Here's a recipe that will work
(commands are given in MS-DOS/Windows form):
<pre>
> cd CGI.pm-2.73
> copy CGI.pm C:\Perl\lib
> mkdir C:\Perl\lib\CGI
> copy CGI\*.pm C:\Perl\lib\CGI
</pre>
Modify this recipe if your Perl library has a different location.
<p>
For Macintosh users, just drag the file named CGI.pm into the folder
where your other Perl .pm files are stored. Also drag the subfolder
named "CGI".
<p>
<STRONG>If you do not have sufficient privileges to install into
/usr/local/lib/perl5</STRONG>, you can still use CGI.pm. Modify the
installation recipe as follows:
<PRE>
% perl Makefile.PL INSTALLDIRS=site INSTALLSITELIB=/home/your/private/dir
% make
% make install
</PRE>
Replace <cite>/home/your/private/dir</cite> with the full path to the
directory you want the library placed in. Now preface your CGI
scripts with a preamble something like the following:
<blockquote><pre>
use lib '/home/your/private/dir';
use CGI;
</pre></blockquote>
Be sure to replace /home/your/private/dir with the true location of
CGI.pm.
<P>
<A HREF="#non_unix">Notes on using CGI.pm in NT and other non-Unix platforms</A>
<hr>
<h2><a name="functionvsoo">Function-Oriented vs Object-Oriented Use</a></h2>
CGI.pm can be used in two distinct modes called
<cite>function-oriented</cite> and <cite>object-oriented</cite>. In
the function-oriented mode, you first import CGI functions into your
script's namespace, then call these functions directly. A simple
function-oriented script looks like this:
<blockquote><pre>
#!/usr/local/bin/perl
use CGI qw/:standard/;
print header(),
start_html(-title=>'Wow!'),
h1('Wow!'),
'Look Ma, no hands!',
end_html();
</pre></blockquote>
The <cite>use</cite> operator loads the CGI.pm definitions and imports
the ":standard" set of function definitions. We then make calls to
various functions such as <cite>header()</cite>, to generate the HTTP
header, <cite>start_html()</cite>, to produce the top part of an HTML
document, <cite>h1()</cite> to produce a level one header, and so
forth.
<p>
In addition to the standard set, there are many optional sets of less
frequently used CGI functions. See <a href="#import">Importing CGI
Methods</a> for full details.
<p>
In the object-oriented mode, you <cite>use CGI;</cite> without
specifying any functions or function sets to import. In this case,
you communicate with CGI.pm via a CGI object. The object is created
by a call to <cite>CGI::new()</cite> and encapsulates all the state
information about the current CGI transaction, such as values of the
CGI parameters passed to your script. Although more verbose, this
coding style has the advantage of allowing you to create multiple CGI
objects, save their state to disk or to a database, and otherwise
manipulate them to achieve neat effects.
<p>
The same script written using the object-oriented style looks like
this:
<blockquote><pre>
#!/usr/local/bin/perl
use CGI;
$q = new CGI;
print $q->header(),
$q->start_html(-title=>'Wow!'),
$q->h1('Wow!'),
'Look Ma, no hands!',
$q->end_html();
</pre></blockquote>
The object-oriented mode also has the advantage of consuming somewhat
less memory than the function-oriented coding style. This may be of
value to users of persistent Perl interpreters such as <a
href="http://perl.apache.org">mod_perl</a>.
<p>
Many of the code examples below show the object-oriented coding
style. Mentally translate them into the function-oriented style if
you prefer.
<H2><A NAME="query">Creating a new CGI object</A></H2>
The most basic use of CGI.pm is to get at the query parameters
submitted to your script. To create a new CGI object that
contains the parameters passed to your script, put the following
at the top of your perl CGI programs:
<PRE>
use CGI;
$query = new CGI;
</PRE>
In the object-oriented world of Perl 5, this code calls the new()
method of the CGI class and stores a new CGI object into the variable
named $query. The new() method does all the dirty work of parsing
the script parameters and environment variables and stores its results
in the new object. You'll now make method calls with this object to
get at the parameters, generate form elements, and do other useful things.
<P>
An alternative form of the new() method allows you to read
script parameters from a previously-opened file handle:
<PRE>
$query = new CGI(FILEHANDLE)
</PRE>
The filehandle can contain a URL-encoded query string, or can be a
series of newline delimited TAG=VALUE pairs. This is compatible with
the save() method. This lets you save the state of a CGI script to a
file and reload it later. It's also possible to save the contents of
several query objects to the same file, either within a single script
or over a period of time. You can then reload the multiple records
into an array of query objects with something like this:
<blockquote><pre>
open (IN,"test.in") || die;
while (!eof(IN)) {
my $q = new CGI(IN);
push(@queries,$q);
}
</pre></blockquote>
You can make simple databases this way, or create a guestbook. If
you're a Perl purist, you can pass a reference to the filehandle glob
instead of the filehandle name. This is the "official" way to pass
filehandles in Perl5:
<blockquote><pre>
my $q = new CGI(\*IN);
</pre></blockquote>
(If you don't know what I'm talking about, then you're not a Perl
purist and you needn't worry about it.)
<p>
If you are using the function-oriented interface and want to
initialize CGI state from a file handle, the way to do this is with
<cite>restore_parameters()</cite>. This will (re)initialize the
default CGI object from the indicated file handle.
<blockquote><pre>
open (IN,"test.in") || die;
restore_parameters(IN);
close IN;
</pre></blockquote>
<p>
You can initialize a CGI object from an associative-array reference.
Values can be either single- or multivalued:
<blockquote><pre>
$query = new CGI({'dinosaur'=>'barney',
'song'=>'I love you',
'friends'=>[qw/Jessica George Nancy/]});
</pre></blockquote>
You can initialize a CGI object by passing a URL-style query string to
the new() method like this:
<blockquote><pre>
$query = new CGI('dinosaur=barney&color=purple');
</pre></blockquote>
Or you can clone a CGI object from an existing one. The parameter
lists of the clone will be identical, but other fields, such as
autoescaping, are not:
<blockquote><pre>
$old_query = new CGI;
$new_query = new CGI($old_query);
</pre></blockquote>
<p>
This form also allows you to create a CGI object that is initially empty:
<blockquote><pre>
$empty_query = new CGI('');
</pre></blockquote>
<p>
If you are using mod_perl, you can initialize a CGI object at any
stage of the request by passing the request object to CGI->new:
<blockquote><pre>
$q = CGI->new($r);
</pre></blockquote>
<p>
To do this with the function-oriented interface, set
Apache->request($r) before calling the first CGI function.
<p>
Finally, you can pass code reference to new() in order to install an
upload_hook function that will be called regularly while a long file
is being uploaded. See <a href="#upload">Creating a File Upload Field</a>
for details.
<p>
See <A HREF="#advanced">advanced techniques</A> for more information.
<H3><A NAME="keywords">Fetching A List Of Keywords From The Query</A></H3>
<PRE>
@keywords = $query->keywords
</PRE>
If the script was invoked as the result of an <ISINDEX> search, the
parsed keywords can be obtained with the keywords() method. This method
will return the keywords as a perl array.
<H3><A NAME="parameters">Fetching The Names Of All The Parameters Passed To Your
Script</A></H3>
<PRE>
@names = $query->param </PRE> If the script was invoked with a
parameter list
(e.g. "name1=value1&name2=value2&name3=value3"), the param()
method will return the parameter names as a list. For backwards
compatibility if the script was invoked as an <ISINDEX> script
and contains a string without ampersands (e.g. "value1+value2+value3")
, there will be a single parameter named "keywords" containing the
"+"-delimited keywords.
<H3><A NAME="values">Fetching The Value(s) Of A Named Parameter</A></H3>
<PRE>
@values = $query->param('foo');
-or-
$value = $query->param('foo');
</PRE>
Pass the param() method a single argument to fetch the value of the
named parameter. If the parameter is multivalued (e.g. from multiple
selections in a scrolling list), you can ask to receive an array. Otherwise
the method will return a single value.
<P>
If a value is not given in the query string, as in the queries
"name1=&name2=" or "name1&name2", it will be returned as an
empty string (not undef). This feature is new in 2.63, and was
introduced to avoid multiple "undefined value" warnings when running
with the -w switch.
<p>
If the parameter does not exist at all, then param() will return undef
in a scalar context, and the empty list in a list context.
<H3><A NAME="setting">Setting The Value(s) Of A Named Parameter</A></H3>
<PRE>
$query->param('foo','an','array','of','values');
-or-
$query->param(-name=>'foo',-values=>['an','array','of','values']);
</PRE>
This sets the value for the named parameter 'foo' to one or more
values. These values will be used to initialize form elements, if
you so desire. Note that this is the one way to forcibly change the value
of a form field after it has previously been set.
<p>
The second example shows an alternative "named parameter" style of function
call that is accepted by most of the CGI methods. See <a href="#named_param">
Calling CGI functions that Take Multiple Arguments</a> for an explanation of
this style.
<H3><A NAME="append">Appending a Parameter</A></H3>
<PRE>
$query->append(-name=>'foo',-values=>['yet','more','values']);
</PRE>
This adds a value or list of values to the named parameter. The
values are appended to the end of the parameter if it already exists.
Otherwise the parameter is created.
<H3><A NAME="deleting">Deleting a Named Parameter Entirely</A></H3>
<PRE>
$query->delete('foo');
</PRE>
This deletes a named parameter entirely. This is useful when you
want to reset the value of the parameter so that it isn't passed
down between invocations of the script.
<H3><A NAME="deleting_all">Deleting all Parameters</A></H3>
<PRE>
$query->delete_all();
</PRE>
This deletes all the parameters and leaves you with an empty CGI
object. This may be useful to restore all the defaults produced by
the form element generating methods.
<H3><A NAME="postdata">Handling non-URLencoded Arguments</A></H3>
<p>
If POSTed data is not of type application/x-www-form-urlencoded or
multipart/form-data, then the POSTed data will not be processed, but
instead be returned as-is in a parameter named POSTDATA. To retrieve
it, use code like this:
<PRE>
my $data = $query->param('POSTDATA');
</PRE>
(If you don't know what the preceding means, don't worry about it. It
only affects people trying to use CGI for XML processing and other
specialized tasks.)
<H3><A NAME="importing">Importing parameters into a namespace</A></H3>
<PRE>
$query->import_names('R');
print "Your name is $R::name\n"
print "Your favorite colors are @R::colors\n";
</PRE>
This imports all parameters into the given name space. For example,
if there were parameters named 'foo1', 'foo2' and 'foo3', after
executing <CODE>$query->import_names('R')</CODE>, the variables
<CODE>@R::foo1, $R::foo1, @R::foo2, $R::foo2,</CODE> etc. would
conveniently spring into existence. Since CGI has no way of
knowing whether you expect a multi- or single-valued parameter,
it creates two variables for each parameter. One is an array,
and contains all the values, and the other is a scalar containing
the first member of the array. Use whichever one is appropriate.
For keyword (a+b+c+d) lists, the variable @R::keywords will be
created.
<P>
If you don't specify a name space, this method assumes namespace "Q".
<p>
An optional second argument to <b>import_names</b>, if present and
non-zero, will delete the contents of the namespace before loading
it. This may be useful for environments like mod_perl in which the
script does not exit after processing a request.
<P><STRONG>Warning</STRONG>: do not import into namespace 'main'. This
represents a major security risk, as evil people could then use this
feature to redefine central variables such as @INC.
CGI.pm will exit with an error if you try to do this.
<p><strong>NOTE:</strong>
Variable names are transformed as necessary into legal Perl
variable names. All non-legal characters are transformed into
underscores. If you need to keep the original names, you should use
the param() method instead to access CGI variables by name.
</p>
<P>
<H3><A NAME="param_fetch">Direct Access to the Parameter List</A></H3>
<blockquote><pre>
$q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
unshift @{$q->param_fetch(-name=>'address')},'George Munster';
</pre></blockquote>
If you need access to the parameter list in a way that isn't covered
by the methods above, you can obtain a direct reference to it by
calling the <b>param_fetch()</b> method with the name of the parameter
you want. This will return an array reference to the named
parameters, which you then can manipulate in any way you like.
<p>
You may call <b>param_fetch()</b> with the name of the CGI parameter,
or with the <b>-name</b> argument, which has the same meaning as
elsewhere.
<h3>Fetching the Parameter List as a Hash</h3>
<blockquote>
<pre>
$params = $q->Vars;
print $params->{'address'};
@foo = split("\0",$params->{'foo'});
%params = $q->Vars;
use CGI ':cgi-lib';
$params = Vars;
</pre>
</blockquote>
<p>
Many people want to fetch the entire parameter list as a hash in which
the keys are the names of the CGI parameters, and the values are the
parameters' values. The <B>Vars()</B> method does this. Called in a
scalar context, it returns the parameter list as a tied hash
reference. Changing a key changes the value of the parameter in the
underlying CGI parameter list. Called in an list context, it returns
the parameter list as an ordinary hash. This allows you to read the
contents of the parameter list, but not to change it.
<p>
When using this, the thing you must watch out for are multivalued CGI
parameters. Because a hash cannot distinguish between scalar and
list context, multivalued parameters will be returned as a packed
string, separated by the "\0" (null) character. You must split this
packed string in order to get at the individual values. This is the
convention introduced long ago by Steve Brenner in his cgi-lib.pl
module for Perl version 4.
<p>
If you wish to use <B>Vars()</B> as a function, import the
<I>:cgi-lib</I> set of function calls (also see the section on <a
href="#migrating">CGI-LIB compatibility</a>).
<h3><A NAME="errors">RETRIEVING CGI ERRORS</A></h3>
<p> Errors can occur while processing user input, particularly when
processing uploaded files. When these errors occur, CGI will stop
processing and return an empty parameter list. You can test for the
existence and nature of errors using the <strong>cgi_error()</strong>
function. The error messages are formatted as HTTP status codes. You
can either incorporate the error text into an HTML page, or use it as
the value of the HTTP status:
<pre>
my $error = $q->cgi_error;
if ($error) {
print $q->header(-status=>$error),
$q->start_html('Problems'),
$q->h2('Request not processed'),
$q->strong($error);
exit 0;
}
</pre>
<p>
When using the function-oriented interface (see the next section),
errors may only occur the first time you call
<strong>param()</strong>. Be prepared for this!
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="saving">Saving the Current State of a Form</A></H2>
<H3>Saving the State to a File</H3>
<PRE>
$query->save(\*FILEHANDLE)
</PRE>
This writes the current query out to the file handle of your choice.
The file handle must already be open and be writable, but other than
that it can point to a file, a socket, a pipe, or whatever. The contents
of the form are written out as TAG=VALUE pairs, which can be reloaded
with the new() method at some later time. You can write out multiple
queries to the same file and later read them into query objects one by one.
<p>
If you wish to use this method from the function-oriented (non-OO)
interface, the exported name for this method is
<cite>save_parameters()</cite>.
See <A HREF="#advanced"> advanced techniques</A> for more information.
<H3><A NAME="self_referencing">
Saving the State in a Self-Referencing URL</A></H3>
<PRE>
$my_url=$query->self_url
</PRE>
This call returns a URL that, when selected, reinvokes this script with
all its state information intact. This is most useful when you want to
jump around within a script-generated document using internal anchors, but
don't want to disrupt the current contents of the form(s). See <A HREF="#advanced">
advanced techniques</A> for an example.
<P>
If you'd like to get the URL without the entire query string appended to
it, use the <code>url()</code> method:
<PRE>
$my_self=$query->url
</PRE>
<h3>Obtaining the Script's URL</h3>
<PRE>
$full_url = $query->url();
$full_url = $query->url(-full=>1); #alternative syntax
$relative_url = $query->url(-relative=>1);
$absolute_url = $query->url(-absolute=>1);
$url_with_path = $query->url(-path_info=>1);
$url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
</PRE>
<code>url()</code> returns the script's URL in a variety of formats.
Called without any arguments, it returns the full form of the URL,
including host name and port number
<pre>
http://your.host.com/path/to/script.cgi
</pre>
You can modify this format with the following named arguments:
<dl>
<dt><strong>-absolute</strong>
<dd>If true, produce an absolute URL, e.g.
<pre>
/path/to/script.cgi
</pre>
<p>
<dt><strong>-relative</strong>
<dd>Produce a relative URL. This is useful if you want to reinvoke your
script with different parameters. For example:
<pre>
script.cgi
</pre>
<p>
<dt><strong>-full</strong>
<dd>Produce the full URL, exactly as if called without any arguments.
This overrides the -relative and -absolute arguments.
<p>
<dt><strong>-path</strong>,<strong>-path_info</strong>
<dd>Append the additional path information to the URL. This can be
combined with -full, -absolute or -relative. -path_info
is provided as a synonym.
<p>
<dt><strong>-query</strong> (<strong>-query_string</strong>)
<dd>Append the query string to the URL. This can be combined with
-full, -absolute or -relative. -query_string is provided
as a synonym.
</dl>
<H3>Mixing POST and URL Parameters</H3>
<pre>
$color = $query->url_param('color');
</pre>
It is possible for a script to receive CGI parameters in the URL as
well as in the fill-out form by creating a form that POSTs to a URL
containing a query string (a "?" mark followed by arguments). The
<b>param()</b> method will always return the contents of the POSTed
fill-out form, ignoring the URL's query string. To retrieve URL
parameters, call the <b>url_param()</b> method. Use it in the same
way as <b>param()</b>. The main difference is that it allows you to
read the parameters, but not set them.
<p>
Under no circumstances will the contents of the URL query string
interfere with similarly-named CGI parameters in POSTed forms. If you
try to mix a URL query string with a form submitted with the GET
method, the results will not be what you expect.
<p>
<A HREF="#contents">Table of contents</A>
<HR>
<H3><A NAME="named_param">
Calling CGI Functions that Take Multiple Arguments</A>
</H3>
In versions of CGI.pm prior to 2.0, it could get difficult to remember
the proper order of arguments in CGI function calls that accepted five
or six different arguments. As of 2.0, there's a better way to pass
arguments to the various CGI functions. In this style, you pass a
series of name=>argument pairs, like this:
<PRE>
$field = $query->radio_group(-name=>'OS',
-values=>[Unix,Windows,Macintosh],
-default=>'Unix');
</PRE>
The advantages of this style are that you don't have to remember the
exact order of the arguments, and if you leave out a parameter, it
will usually default to some reasonable value. If you provide
a parameter that the method doesn't recognize, it will usually do
something useful with it, such as incorporating it into the HTML
tag as an attribute. For example if Netscape decides next week to add a new
JUSTIFICATION parameter to the text field tags, you can start using
the feature without waiting for a new version of CGI.pm:
<PRE>
$field = $query->textfield(-name=>'State',
-default=>'gaseous',
-justification=>'RIGHT');
</PRE>
This will result in an HTML tag that looks like this:
<PRE>
<INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
JUSTIFICATION="RIGHT">
</PRE>
Parameter names are case insensitive: you can use -name, or -Name or
-NAME.
Actually, CGI.pm only looks for a hyphen in the first parameter. So
you can leave it off subsequent parameters if you like. Something to
be wary of is the potential that a string constant like "values" will
collide with a keyword (and in fact it does!) While Perl usually
figures out when you're referring to a function and when you're
referring to a string, you probably should put quotation marks around
all string constants just to play it safe.
<P>
HTML/HTTP parameters that contain internal hyphens, such as <i>-Content-language</i>
can be passed by putting quotes around them, or by using an underscore
for the second hyphen, e.g. <cite>-Content_language</cite>.
<p>
The fact that you must use curly {} braces around the attributes
passed to functions that create simple HTML tags but don't use them
around the arguments passed to all other functions has many people,
including myself, confused. As of 2.37b7, the syntax is extended to
allow you to use curly braces for all function calls:
<PRE>
$field = $query->radio_group({-name=>'OS',
-values=>[Unix,Windows,Macintosh],
-default=>'Unix'});
</PRE>
<A HREF="#contents">Table of contents</A>
<HR>
<H2><A NAME="header">
Creating the HTTP Header</A>
</H2>
<H3><A NAME="standard_header">
Creating the Standard Header for a Virtual Document</A>
</H3>
<PRE>
print $query->header('image/gif');
</PRE>
This prints out the required HTTP Content-type: header and the requisite
blank line beneath it. If no parameter is specified, it will default to
'text/html'.
<P>
An extended form of this method allows you to specify a status code
and a message to pass back to the browser:
<PRE>
print $query->header(-type=>'image/gif',
-status=>'204 No Response');
</PRE>
This presents the browser with a status code of 204 (No response).
Properly-behaved browsers will take no action, simply remaining on the
current page. (This is appropriate for a script that does some
processing but doesn't need to display any results, or for a script
called when a user clicks on an empty part of a clickable image map.)
<P>
Several other named parameters are recognized. Here's a
contrived example that uses them all:
<PRE>
print $query->header(-type=>'image/gif',
-status=>'402 Payment Required',
-expires=>'+3d',
-cookie=>$my_cookie,
-charset=>'UTF-7',
-attachment=>'foo.gif',
-Cost=>'$0.02');
</PRE>
<h4>-expires</h4>
Some browsers, such as Internet Explorer, cache the output of CGI
scripts. Others, such as Netscape Navigator do not. This leads to
annoying and inconsistent behavior when going from one browser to
another. You can force the behavior to be consistent by using the
<strong>-expires</strong> parameter. When you specify an absolute or
relative expiration interval with this parameter, browsers and
proxy servers will cache the script's output until the indicated
expiration date. The following forms are all valid for the
<strong>-expires</strong> field: <pre>
+30s 30 seconds from now
+10m ten minutes from now
+1h one hour from now
-1d yesterday (i.e. "ASAP!")
now immediately
+3M in three months
+10y in ten years time
Thu, 25-Apr-1999 00:40:33 GMT at the indicated time & date
</pre>
When you use <strong>-expires</strong>, the script also generates a
correct time stamp for the generated document to ensure that your
clock and the browser's clock agree. This allows you to create
documents that are reliably cached for short periods of time.
<p>
<strong>CGI::expires()</strong> is the static function call used internally that turns
relative time intervals into HTTP dates. You can call it directly if
you wish.
<h4>-cookie</h4>
The <strong>-cookie</strong> parameter generates a header that tells
Netscape browsers to return a "magic cookie" during all subsequent
transactions with your script. HTTP cookies have a special format
that includes interesting attributes such as expiration time. Use the
<a href="#cookies">cookie()</a> method to create and retrieve session
cookies. The value of this parameter can be either a scalar value or
an array reference. You can use the latter to generate multiple
cookies. (You can use the alias <strong>-cookies</strong> for
readability.)
<h4>-nph</h4>
The <strong>-nph</strong> parameter, if set to a non-zero value, will
generate a valid header for use in no-parsed-header scripts. For
example:
<blockquote><pre>
print $query->header(-nph=>1,
-status=>'200 OK',
-type=>'text/html');
</pre></blockquote>
You will need to use this if:
<ol>
<li>You are using Microsoft Internet Information Server.
<li>If you need to create unbuffered output, for example for use
in a "server push" script.
<li>To take advantage of HTTP extensions not supported by your server.
</ol>
See <a href="#nph">Using NPH Scripts</a> for more information.
<h4>-charset</h4>
The <b>-charset</b> parameter can be used to control the character set
sent to the browser. If not provided, defaults to ISO-8859-1. As a
side effect, this calls the charset() method to set the behavior for
escapeHTML().
<h4>-attachment</h4>
The <b>-attachment</b> parameter can be used to turn the page into an
attachment. Instead of displaying the page, some browsers will prompt
the user to save it to disk. The value of the argument is the
suggested name for the saved file. In order for this to work, you may
have to set the <b>-type</b> to "application/octet-stream".
<h4>-p3p</h4>