📄 ch19.htm
字号:
<HTML><HEAD><TITLE>Chapter 19 -- What Is CGI?</TITLE><META></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#0000EE" VLINK="#551A8B" ALINK="#CE2910"><H1><FONT SIZE=6 COLOR=#FF0000>Chapter 19</FONT></H1><H1><FONT SIZE=6 COLOR=#FF0000>What Is CGI?</FONT></H1><HR><P><CENTER><B><FONT SIZE=5>CONTENTS</FONT></B></CENTER><UL><LI><A HREF="#WhyUsePerlforCGI">Why Use Perl for CGI?</A><LI><A HREF="#CGIAppsversusJavaApplets">CGI Apps versus Java Applets</A><LI><A HREF="#ShouldYouUseCGIModules">Should You Use CGI Modules?</A><LI><A HREF="#HowDoesCGIWork">How Does CGI Work?</A><LI><A HREF="#CallingYourCGIProgram">Calling Your CGI Program</A><LI><A HREF="#YourFirstCGIProgram">Your First CGI Program</A><LI><A HREF="#WhyAreFilePermissionsImportantinUNIX">Why Are File Permissions Important in UNIX?</A><LI><A HREF="#HTTPHeaders">HTTP Headers</A><LI><A HREF="#CGIandEnvironmentVariables">CGI and Environment Variables</A><LI><A HREF="#URLENCoding">URL ENCoding</A><LI><A HREF="#Security">Security</A><LI><A HREF="#CGIwrapandSecurity">CGIwrap and Security</A><LI><A HREF="#Cookies">Cookies</A><UL><LI><A HREF="#CookieSecurity">Cookie Security</A><LI><A HREF="#HowAreCookiesCreatedandRead">How Are Cookies Created and Read?</A><LI><A HREF="#CanaVisitorsBrowserSupportCookies">Can a Visitor's Browser Support Cookies?</A></UL><LI><A HREF="#DebuggingCGIPrograms">Debugging CGI Programs</A><UL><LI><A HREF="#SendingOutputtotheServersLogFile">Sending Output to the Server's Log File</A><LI><A HREF="#SendingSTDERRtotheWebBrowser">Sending STDERR to the Web Browser</A><LI><A HREF="#CGITap">CGITap</A><LI><A HREF="#GeneratinganErrorHTMLPage">Generating an Error HTML Page</A></UL><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>CGI, or <I>Common Gateway Interface</I>, is the standard programminginterface between Web servers and external programs. It is oneof the most exciting and fun areas of programming today. The CGIstandard lets Web browsers pass information to programs writtenin any language. If you want to create a lightning-fast searchengine, then your CGI program will most likely be written in Cor C++. However, most other applications can use Perl.<P>The CGI standard does not exist in isolation; it is dependenton the HTML and HTTP standards. HTML is the standard that letsWeb browsers understand document content. HTTP is the communicationsprotocol that, among other things, lets Web servers talk withWeb browsers.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Note</B></TD></TR><TR><TD><BLOCKQUOTE>If you are unfamiliar with HTML, you might want to skip to the HTML introduction in <A HREF="ch20.htm" >Chapter 20</A>, "Form Processing," before continuing. Otherwise, take the HTML refereNCes in this chapter at face value.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Almost anyone can throw together some HTML and hang a "homepage" out on the Web. But most sites out there are, quitefrankly, boring. Why? The fact is that most sites are built asa simple series of HTML documents that never change. The siteis completely static. No one is likely to visit a static pagemore than oNCe or twice. Think about the sites you visit mostoften. They probably have some interesting content, certainly,but more importantly, they have dynamic content.<P>So what's a Webmaster to do? No Webmaster has the time to updatehis or her Web site by hand every day. Fortunately, the peoplewho developed the Web protocol thought of this problem and gaveus CGI. CGI gives you a way to make Web sites dynamic and interactive.<P>Each word in the acronym Common Gateway Interface helps you tounderstand the interface:<UL><LI><B>Common</B>-interacts with many different operating systems.<LI><B>Gateway</B>-provides users with a way to gain access todifferent programs, such as databases or picture generators.<LI><B>Interface</B>-uses a well-defined method to interact witha Web server.</UL><P>CGI applications can perform nearly any task that your imaginationcan think up. For example, you can create Web pages on-the-fly,access databases, hold telnet sessions, generate graphics, andcompile statistics.<P>The basic coNCept behind CGI is pretty simple; however, actuallycreating CGI applications is not. That requires real programmingskills. You need to be able to debug programs and make logicalconnections between one idea and another. You also need to havethe ability to visualize the application that you'd like to create.This chapter and the next, "Form Processing," will getyou started with CGI programming. If you plan to create largeapplications, you might want to look at Que's <I>Special EditionUsing CGI</I>.<H2><A NAME="WhyUsePerlforCGI"><FONT SIZE=5 COLOR=#FF0000>Why Use Perl for CGI?</FONT></A></H2><P>Perl is the de facto standard for CGI programming for a numberof reasons, but perhaps the most important are:<UL><LI><B>Socket Support</B>-create programs that interface seamlesslywith Internet protocols. Your CGI program can send a Web pagein response to a transaction and send a series of e-mail messagesto inform interested people that the transaction happened.<LI><B>Pattern Matching</B>-ideal for handling form data and searchingtext.<LI><B>Flexible Text Handling</B>-no details to worry. The waythat Perl handles strings, in terms of memory allocation and deallocation,fades into the background as you program. You simply can ignorethe details of coNCatenating, copying, and creating new strings.</UL><P>The advantage of an interpreted language in CGI applications isits simplicity in development, debugging, and revision. By removingthe compilation step, you and I can move more quickly from taskto task, without the frustration that can sometimes arise fromdebugging compiled programs. Of course, not any interpreted languagewill do. Perl has the distiNCt advantage of having an extremelyrich and capable fuNCtionality.<P>There are some times when a mature CGI application should be portedto C or another compiled language. These are the Web applicationswhere speed is important. If you expect to have a very activesite, you probably want to move to a compiled language becausethey run faster.<H2><A NAME="CGIAppsversusJavaApplets"><FONT SIZE=5 COLOR=#FF0000>CGI Apps versus Java Applets</FONT></A></H2><P>CGI and Java are two totally different animals. CGI is a specificationthat can be used by any programming language. CGI applicationsare run on a Web server. Java is a programming language that isrun on the client side.<P>CGI applications should be designed to take advantage of the centralizednature of a Web server. They are great for searching databases,processing HTML form data, and other applications that requirelimited interaction with a user.<P>Java applications are good when you need a high degree of interactionwith users: for example, games or animation.<P>Java programs need to be kept relatively small because they aretransmitted through the Internet to the client. CGI applications,on the other hand, can be as large as needed because they resideand are executed on the Web server.<P>You can design your Web site to use both Java and CGI applications.For example, you might want to use Java on the client side todo field validation when collecting information on a form. ThenoNCe the input has been validated, the Java application can sendthe information to a CGI application on the Web server where thedatabase resides.<H2><A NAME="ShouldYouUseCGIModules"><FONT SIZE=5 COLOR=#FF0000>Should You Use CGI Modules?</FONT></A></H2><P>I eNCourage you to use the CGI modules that are available on theInternet. The most up-to-date module that I know about is called<TT>cgi.pm</TT>-but you must be usingPerl v5.002 or an even newer version in order to use it. <TT>cgi.pm</TT>is very comprehensive and covers many different protocols in additionto the basic CGI standard.<P>You might find that <TT>cgi.pm</TT>is overkill for simple CGI applications. If so, look at <TT>cgi-lite.pl</TT>.This library doesn't do as much as <TT>cgi.pm</TT>but you'll probably find that it is easier to use.<P>You can find both of these scripts at one of the CPAN Web sitesthat are mentioned in <A HREF="ch22.htm" >Chapter 22</A>, "Internet Resources."<P>However, in this book, I have purposely not used these scripts.I feel it is important for you to understand the mechanisms behindthe protocols. This will make debugging your applications easierbecause you'll have a better idea what the modules are doing behindthe scenes. You will also be able to make better use of pre-existingmodules if you can make educated guesses about what a poorly documentedfuNCtion does.<H2><A NAME="HowDoesCGIWork"><FONT SIZE=5 COLOR=#FF0000>How Does CGI Work?</FONT></A></H2><P>CGI programs are always placed on a disk that the Web server hasaccess to. This means that if you are using a dial-up accountto maintain your Web site, you need to upload your CGI programsto the server before they can be run.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Tip</B></TD></TR><TR><TD><BLOCKQUOTE>You can test your scripts locally as long as you can use Perl on your local machine. See the "Debugging" section later in this chapter.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Web servers are generally configured so that all CGI applicationsare placed into a <TT>cgi-bin</TT>directory. However, the Web server may have aliases so that "virtualdirectories" exist. Each user might have his or her own <TT>cgi-bin</TT>directory. The directory location is totally under the controlof your Web site administrator.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Tip</B></TD></TR><TR><TD><BLOCKQUOTE>Finding out which directory your scripts need to be placed in is the first step in creating CGI programs. Because you need to get this information from your Web site administrator, send an e-mail message right now requesting this information. Also ask if there are any CGI restrictions or guidelines that you need to follow.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="CallingYourCGIProgram"><FONT SIZE=5 COLOR=#FF0000>Calling Your CGI Program</FONT></A></H2><P>The easiest way to run a CGI program is to type in the URL ofthe program into your Web browser. The Web server should recognizethat you are requesting a CGI program and execute it. For example,if you already had a CGI program called <TT>test.pl</TT>running on a local Web server, you could start it by enteringthe following URL into your Web browser:<BLOCKQUOTE><PRE>http://localhost/cgi-bin/test.pl</PRE></BLOCKQUOTE><P>The Web server will execute your CGI script and any output isdisplayed by your Web browser.<P>The URL for your CGI program is a <I>virtual</I> path. The actuallocation of the script on the Web server depends on the configurationof the server software and the type of computer being used. Forexample, if your computer is running the Linux operating systemand the NCSA Web server in a "standard" configuration,then the above virtual would translate into <TT>/usr/local/etc/httpd/cgi-bin/test.pl</TT>.If you were running the Website server under Windows 95, the translatedpath might be <TT>/website/cgi-shl/test.pl</TT>.<P>If you have installed and are administering the Web server yourself,you probably know where to place your scripts. If you are usinga service provider's Web server, ask the server's administratorwhere to put your scripts and how to refereNCe them from yourdocuments.<P>There are other ways to invoke CGI programs besides using a Webbrowser to visit the URL. You can also start CGI programs from:<UL><LI>a hypertext link. For example:</UL><BLOCKQUOTE><PRE><A HREF="cgi-bin/test.pl">Click here to run a CGI program</A></PRE></BLOCKQUOTE><UL><LI>a button on an HTML form. You can read more about HTML formsin <A HREF="ch20.htm" >Chapter 20</A>, "Form Processing."<LI>a server-side iNClude. You can read more about server-sideiNCludes in <A HREF="ch20.htm" >Chapter 20</A>, "Form Processing."</UL><P>Interestingly enough, you can pass information to your CGI programby adding extra information to the standard URL. If your CGI programis used for searching your site, for example, you can pass someinformation to specify which directory to search. The followingHTML hyperlink will invoke a search script and tell it to searchthe <TT>/root/document</TT> directory.<BLOCKQUOTE><PRE><A HREF="cgi-bin/search.pl/root/document">Search the Document Directory <A></PRE></BLOCKQUOTE><P>This <I>extra</I> path information can be accessed through the<TT>PATH_INFO</TT> environment variable.<P>You can also use a question mark to pass information to a CGIprogram. Typically, a question mark indicates that you are passingkeywords that will be used in a search.<BLOCKQUOTE><PRE><A HREF="cgi-bin/search.pl?Wine+1993">Search for 1993 Wines</A></PRE></BLOCKQUOTE><P>The information that follows the question mark will be availableto your CGI program through the <TT>QUERY_STRING</TT>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -