⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch19_02.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 19.1. Writing a CGI Script (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:45:13Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch19_01.htm"TITLE="19. CGI Programming"><LINKREL="prev"HREF="ch19_01.htm"TITLE="19.0. Introduction"><LINKREL="next"HREF="ch19_03.htm"TITLE="19.2. Redirecting Error Messages"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch19_01.htm"TITLE="19.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 19.0. Introduction"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch19_01.htm"TITLE="19. CGI Programming"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch19_03.htm"TITLE="19.2. Redirecting Error Messages"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 19.2. Redirecting Error Messages"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch19-39842">19.1. Writing a CGI Script</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch19-pgfId-176">Problem<ACLASS="indexterm"NAME="ch19-idx-1000005362-0"></A><ACLASS="indexterm"NAME="ch19-idx-1000005362-1"></A><ACLASS="indexterm"NAME="ch19-idx-1000005362-2"></A></A></H3><PCLASS="para">You want to write a CGI script to process the contents of an HTML form. In particular, you want to access the form contents, and produce valid output in return.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch19-pgfId-182">Solution</A></H3><PCLASS="para">A CGI script is a server-side program launched by a web server to generate a dynamic document. It receives encoded information from the remote client (user's browser) via STDIN and environment variables, and it must produce a valid HTTP header and body on STDOUT. The standard CGI module, shown in <ACLASS="xref"HREF="ch19_02.htm#ch19-13957"TITLE="hiweb">Example 19.1</A>, painlessly manages the encoding of input and output.</P><DIVCLASS="example"><H4CLASS="example"><ACLASS="title"NAME="ch19-13957">Example 19.1: hiweb</A></H4><PRECLASS="programlisting">#!/usr/bin/perl -w# <ACLASS="indexterm"NAME="ch19-idx-1000005368-0"></A>hiweb - load CGI module to decode information given by web serveruse strict;use CGI qw(:standard escapeHTML);# get a parameter from a formmy $value = param('PARAM_NAME');# output a documentprint header(), start_html(&quot;Howdy there!&quot;),      p(&quot;You typed: &quot;, tt(escapeHTML($value))),      end_html();</PRE></DIV></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch19-pgfId-214">Discussion</A></H3><PCLASS="para">CGI is just a protocol, a formal agreement between a web server and a separate program. The server encodes the client's form input data, and the CGI program decodes the form and generates output. The protocol says nothing regarding which language the program must be written in; programs and scripts that obey the CGI protocol have been written in C, shell, Rexx, C++, VMS DCL, Smalltalk, Tcl, Python, and (of course) Perl.</P><PCLASS="para">The full CGI specification lays out which environment variables hold which data (such as form input parameters) and how it's all encoded. In theory, it should be easy to follow the protocol to decode the input, but in practice, it is surprisingly tricky to get right. That's why we <EMCLASS="emphasis">strongly</EM> recommend using Lincoln Stein's excellent CGI module. The hard work of handling the CGI requirements correctly and conveniently has already been done, freeing you to write the core of your program without tedious network protocols.</P><PCLASS="para">CGI scripts are called in two main ways, referred to as <EMCLASS="emphasis">methods</EM><ACLASS="indexterm"NAME="ch19-idx-1000005369-0"></A><ACLASS="indexterm"NAME="ch19-idx-1000005369-1"></A><ACLASS="indexterm"NAME="ch19-idx-1000005369-2"></A><ACLASS="indexterm"NAME="ch19-idx-1000005369-3"></A> &nbsp;-  but don't confuse HTTP methods with Perl object methods! The HTTP GET method is used in document retrievals where an identical request will produce an identical result, such as a dictionary lookup. A GET stores form data in the URL. This means it can be conveniently bookmarked for canned requests, but has limitations on the total size of the data requested. The HTTP <ACLASS="indexterm"NAME="ch19-idx-1000005374-0"></A>POST method sends form data separate from the request. It has no such size limitations, but cannot be bookmarked. Forms that update information on the server, like mailing in feedback or modifying a database entry, should use POST. Client browsers and intervening proxies are free to cache and refresh the results of GET requests behind your back, but they may not cache POST requests. GET is only safe for short read-only requests, whereas POST is safe for forms of any size, as well as for updates and feedback responses. Therefore, by default, the CGI module uses POST for all forms it generates.</P><PCLASS="para">With a few exceptions mainly related to file permissions and highly interactive work, CGI scripts can do nearly anything any other program can do. They can send back results in many formats: plain text, HTML documents, sound files, pictures, or anything else specified in the HTTP header. Besides producing plain text or HTML text, they can also redirect the client browser to another location, set server cookies, request authentication, and give errors.</P><PCLASS="para">The <ACLASS="indexterm"NAME="ch19-idx-1000005628-0"></A>CGI module provides two different interfaces, a procedural one for casual use, and an object-oriented one for power users with complicated needs. Virtually all CGI scripts should use the simple procedural interface, but unfortunately, most of CGI.pm's documentation uses examples with the original object-oriented approach. Due to backwards compatibility, if you want the simple procedural interface, you need to specifically ask for it using the <CODECLASS="literal">:standard</CODE> import tag. See <ACLASS="xref"HREF="ch12_01.htm"TITLE="Packages, Libraries, and Modules">Chapter 12, <CITECLASS="chapter">Packages, Libraries, and Modules</CITE></A>, for more on import tags.</P><PCLASS="para">To read the user's form input, pass the <CODECLASS="literal">param</CODE> function a field name to get. If you had a form field name "favorite", then <CODECLASS="literal">param(&quot;favorite&quot;)</CODE> would return its value. With some types of form fields like scrolling lists, the user can choose more than one option. For these, <CODECLASS="literal">param</CODE> returns a list of values, which you could assign to an array.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch19-idx-1000005376-0"></A>For example, here's a script that pulls in values of three form fields, the last one having many return values:</P><PRECLASS="programlisting">use CGI qw(:standard);$who   = param(&quot;Name&quot;);$phone = param(&quot;Number&quot;);@picks = param(&quot;Choices&quot;);</PRE><PCLASS="para">Called without any arguments, <CODECLASS="literal">param</CODE> returns a list of valid form parameters in list context, or in scalar context, how many form parameters there were.</P><PCLASS="para">That's all there is to accessing the user's input. Do with it whatever you please, and then generate properly formatted output. This is nearly as easy. Remember that unlike regular programs, a CGI script's output must be formatted in a particular way: it must first emit a set of headers followed by a blank line before it can produce normal output.</P><PCLASS="para">As shown in the Solution above, the CGI module helps with output as well as input. The module provides functions for generating HTTP headers and HTML code. The <CODECLASS="literal">header</CODE> function builds the text of a header for you. By default, it produces headers for a <CODECLASS="literal">text/html</CODE> document, but you can change the Content-Type and supply other optional header parameters as well:</P><PRECLASS="programlisting">print header( -TYPE    =&gt; 'text/plain',              -EXPIRES =&gt; '+3d' );</PRE><PCLASS="para">CGI.pm can also be used to generate HTML. It may seem trivial, but this is where the CGI module shines: the creation of dynamic forms, especially stateful ones such as shopping carts. The CGI module even has functions for generating forms and tables.</P><PCLASS="para">When printing form widgets, the characters <CODECLASS="literal">&amp;</CODE>, &lt;, &gt;, and <CODECLASS="literal">&quot;</CODE> in HTML output are automatically replaced with their entity equivalents. This is not the case with arbitary user output. That's why the Solution imports and makes use of the <CODECLASS="literal">escapeHTML</CODE> function &nbsp;-  if the user types any of those special characters, they won't cause formatting errors in the HTML.</P><PCLASS="para">For a full list of functions and their calling conventions, see <ACLASS="indexterm"NAME="ch19-idx-1000005377-0"></A>CGI.pm's documentation, included as POD source within the module itself. <ACLASS="indexterm"NAME="ch19-idx-1000005364-0"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch19-pgfId-256">See Also</A></H3><PCLASS="para"><ACLASS="systemitem.url"HREF="http://www.w3.org/CGI/">http://www.w3.org/CGI/</A>; <ACLASS="xref"HREF="ch19_08.htm"TITLE="Formatting Lists and Tables with HTML Shortcuts">Recipe 19.7</A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch19_01.htm"TITLE="19.0. Introduction"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 19.0. Introduction"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch19_03.htm"TITLE="19.2. Redirecting Error Messages"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 19.2. Redirecting Error Messages"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">19.0. Introduction</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">19.2. Redirecting Error Messages</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -