CGI Programming With Perl - Perl Training

Transcription

CGI Programmingwith Perl#!/usr/bin/perl# It Came From the Crypt! q q&9RM8 ba1cHtJprcG6SJ3dkaQM8 p jp8vsYi3UnT o E0PUR b zYb3 EQiZrZiIm6Nc81WY qs U g7m QzHM2VjY62II5Bg7N e kkt 7 5JLD86&; u q s &\s&&xg&& 2;@v unpackq&c3&,qq&i\nm&;unshift@v,2**2*2**2*2;%l map{chr }reverse@v; i 2*2*2&& q, q i&&8; while( i m& [ *]{ q}&x){ y substr(crypt( &, &), u,print);print! l{ y}&& yne"y"? y: l{ y} ; i s & x} y m&ymum my&Kirrily RobertPaul FenwickJacinta Richardson

CGI Programming with Perlby Kirrily Robert, Paul Fenwick, and Jacinta RichardsonCopyright 1999-2000 by Netizen Pty LtdCopyright 2000 by Kirrily RobertCopyright 2001 by Obsidian Consulting Group Pty LtdCopyright 2001-2004 by Paul FenwickCopyright 2001-2004 by Jacinta RichardsonCopyright 2001-2004 by Perl Training AustraliaOpen Publications License 1.0Cover artwork Copyright (c) 2001 Joe Lesko. Used with permission.This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latestversion is presently available at http://www.opencontent.org/openpub/).Distribution of this work or derivative of this work in any standard (paper) book form is prohibited unless prior permission is obtained fromthe copyright holder.This document is a greatly revised and edited copy of the training notes originally created by Kirrily Robert and Netizen Pty Ltd. Theserevisions were made by Paul Fenwick and Jacinta Richardson.Copies of the original training manuals can be found at http://sourceforge.net/projets/sporkCopies of the Obsidian training manuals can be found at http://www.obsidian.com.au/trainingThis training manual is maintained by Perl Training Australia, and can be found at http://www.perltraining.com.au/notes.htmlThis is version 4.1 of Perl Training Australia’s "Perl Programming with CGI" training manual.

Table of Contents1. Introduction. 1Course outline . 1Assumed knowledge . 1Module objectives . 1Platform and version details. 1The course notes. 2Other materials . 32. What is CGI?. 5In this chapter. . 5Definition of CGI . 5Introduction to HTTP. 5Terminology . 6HTTP Methods . 6GET. 6HEAD . 6POST. 6What is needed to run Perl CGI programs? . 7Chapter summary . 73. Generating web pages with Perl . 9In this chapter. . 9Your public html directory . 9The CGI directory . 9CGI.pm. Making CGI programming a breeze. . 9That header thing. 10Quoting and roll-your-own quotes. 11Exercises. 12HTML output . 12HTML tags with CGI.pm . 12Faking tags with CGI.pm . 13Then again, why bother? (CGI D.W.I.M). 14Running your CGI program . 15Exercises. 15Debugging your CGI programs. 15Failing gracefully with CGI::Carp. 15Exercises. 16Cookies. 16Exercises. 18Environment variables. 18Exercises. 18Chapter summary . 184. HTML forms and CGI.pm. 21In this chapter. . 21A quick look at HTML forms . 21The FORM element . 21Printing your form with CGI.pm . 21CGI.pm FORM defaults. 21Form input fields and CGI.pm . 22TEXT. 22Perl Training Australia (http://www.perltraining.com.au/)v

HIDDEN. 22PASSWORD. 23CHECKBOX . 23CHECKBOX GROUP. 23SELECT . 25SUBMIT . 25Exercises. 26Chapter summary . 265. Accepting and processing form input . 27In this chapter. . 27CGI Parameters . 27Calling param() in context . 27Where this hurts . 28What were my parameters again?. 28Debugging with the CGI.pm module’s offline mode . 28Exercises. 29Building a GET string . 30Practical Exercise: Data validation . 30Exercises. 31Practical Exercise: Multi-form "Wizard" interface . 31Exercises. 33Practical Exercise: File upload. 33Chapter summary . 346. Security issues . 35In this chapter. . 35Authentication and access control for CGI scripts. 35Why is CGI authentication a bad idea? . 35HTTP authentication . 35Why is HTTP authentication a bad idea? . 36Access control . 36Tainted data . 36Exercises. 37Secure HTTP. 37Chapter summary . 387. Splitting HTML and code with HTML::Template. 39In this chapter. . 39What is HTML::Template . 39The Template Explained . 40Conventions . 40Simple Template Fields . 41Exercises . 41Escaping in template fields. 41Conditionals. 42Exercises . 43Looping constructs . 43Including files . 44Using Template Objects . 44Binding simple parameters . 44Binding complex parameters . 45Exercises. 46viPerl Training Australia (http://www.perltraining.com.au/)

Associating other objects. 46Chapter Summary . 478. Conclusion . 49What you’ve learnt . 49Where to now? . 49Further reading . 49Books. 50Online . 50A. Unix cheat sheet . 51B. Editor cheat sheet. 53vi (or vim) . 53Running . 53Using. 53Exiting . 53Gotchas . 53Help . 54nano (pico clone). 54Running . 54Using. 54Exiting . 54Gotchas . 54Help . 54C. ASCII Pronunciation Guide . 55D. HTML Cheat Sheet. 57E. HTTP Terminology and reference. 59Terminology . 59HTTP status codes . 60Colophon. 61Perl Training Australia (http://www.perltraining.com.au/)vii

viiiPerl Training Australia (http://www.perltraining.com.au/)

List of Tables4-1. FORM element attributes . 214-2. CGI.pm FORM defaults . 22A-1. Simple Unix commands . 51B-1. Layout of editor cheat sheets . 53C-1. ASCII Pronunciation Guide. 55D-1. Basic HTML elements. 57E-1. HTTP status codes . 60List of Figures2-1. A typical HTTP and CGI connection . 5Perl Training Australia (http://www.perltraining.com.au/)ix

xPerl Training Australia (http://www.perltraining.com.au/)

Chapter 1. IntroductionWelcome to Perl Training Australia’s CGI Programming with Perl training course. This is a one-daycourse in which you will learn how to write dynamic, interactive web applications using the Perlprogramming language.Course outline What is CGI? Generating web pages with a Perl script HTML forms and CGI.pm Accepting and processing form input Security issues Splitting HTML and code with HTML::TemplateAssumed knowledgeIt is assumed that you know and understand the following topics: Unix - logging in, creating and editing files Perl - variable types, operators and functions, conditional constructs, subroutines, basic regularexpressions Basic HTML - paragraphs, headings, unordered lists, anchor tags, images, etc.If you need help with editing files under Unix, a cheat-sheet is available in Appendix A and an editorcommand summary in Appendix B.The Unix operating system commands you will need are mentioned and explained very brieflythroughout the course - please feel free to ask if you need more help. The required Perl knowledgewas covered in our "Introduction to Perl" course. If you’ve worked with Perl for about a year you’llknow much of the required material. Lastly, an HTML cheat-sheet is provided in Appendix D forthose who need reminding.Module objectives Understand the meaning of CGI and the Hypertext Transfer Protocol Know how to generate simple web pages using Perl Understand how to accept and process data from web forms using the CGI module Understand security issues pertaining to CGI programming and how to avoid security problems Recognise and use a number of Perl modules for purposes related to CGI programmingPerl Training Australia (http://www.perltraining.com.au/)1

Chapter 1. IntroductionPlatform and version detailsThis module is taught using Unix or a Unix-like operating system. Most of what is learnt will workequally well on Windows NT or other operating systems; your instructor will inform you throughoutthe course of any areas which differ.All Perl Training Australia’s Perl training courses use Perl 5, the most recent major release of thePerl language. Perl 5 differs significantly from previous versions of Perl, so you will need a Perl 5interpreter to use what you have learnt. However, older Perl programs should work fine under Perl 5.At the time of writing, the most recent stable release of Perl is version 5.6.1, however older versionsof Perl 5 are still common. Your instructor will inform you of any features which may not exist inolder versions.The web server used for examples in this module is Apache (http://www.apache.org). We havechosen this web server for examples as it is freely available, widely used, and very fast andfull-featured.The course notesThese course notes contain material which will guide you through the topics listed above, as well asappendices containing other useful information.The following typographic conventions are used in these notes:System commands appear in this typefaceLiteral text which you should type in to the command line or editor appears as monospacedfont.Keystrokes which you should type appear like this: ENTER. Combinations of keys appear like this:CTRL-DProgram listings and other literal listings of what appears on thescreen appear in a monospaced font like this.Parts of commands or other literal text which should be replaced by your own specific values appearslike thisNotes and tips appear offset from the text like this.Notes which are marked "Advanced" are for those who are racing ahead or who already havesome knowledge of the topic at hand. The information contained in these notes is not essentialto your understanding of the topic, but may be of interest to those who want to extend theirknowledge.Notes marked with "Readme" are pointers to more information which can be foundin your textbook or in online documentation such as manual pages or websites.2Perl Training Australia (http://www.perltraining.com.au/)

Chapter 1. IntroductionNotes marked "Caution" contain details of unexpected behaviour or traps for the unwary.Other materialsIn addition to these notes, it is highly recommend that you obtain a copy of Programming Perl (2ndor 3rd edition) by Larry Wall, et al., more commonly referred to as "the Camel book". While thesenotes have been developed to be useful in their own right, the Camel book covers an extensive rangeof topics not covered in this course, and discusses the concepts covered in these notes in much moredetail. The Camel Book is considered to be the definitive reference book for the Perl programminglanguage.The page references in these notes refer to the 3rd edition of the camel book. References to the 2ndedition will be shown in parentheses.Perl Training Australia (http://www.perltraining.com.au/)3

Chapter 1. Introduction4Perl Training Australia (http://www.perltraining.com.au/)

Chapter 2. What is CGI?In this chapter.In this section we will define the term CGI and learn how web servers use CGI to provide dynamicand interactive material. We explore the Hypertext Transfer Protocol as it applies to both static andCGI-generated content, and examine raw HTTP requests and responses by telnetting to a web server.Definition of CGICGI is the Common Gateway Interface, a standard for programs to interface with informationservers such as HTTP (web) servers. CGI allows the HTTP server to run an executable program orscript in response to a user request, and generate output on the fly. This allows web developers tocreate dynamic and interactive web pages.CGI programs can be written in any language. Perl is a very common language for CGI programmingas it is largely platform independent and the language’s features make it very easy to write powerfulapplications. However, some CGI programs are written in C, shell script, or other languages.It is important to remember that CGI is not a language in itself. CGI is merely a type of programwhich can be written in any language.Introduction to HTTPTo understand how CGI works, you need some understanding of how HTTP works.HTTP stands for HyperText Transfer Protocol, and (not very surprisingly) is the protocol used fortransferring hypertext documents such as HTML pages on the World Wide Web.For the purposes of this course, we will only be looking at HTTP version 1.0. The current version,1.1, is specified in RFC 2068 and contains many more features, but none of them are necessary for abasic understanding of CGI programming. An HTTP cheat-sheet, containing some commonterminology and a table of status codes, appears in Appendix E.RFCs, or "Request For Comment" documents, can be obtained from the InternetEngineering Task Force (IETF) website (http://www.ietf.org/) or from mirrors such as The RFCmirror at AARNet (http://mirror.aarnet.edu.au/pub/rfc).Figure 2-1. A typical HTTP and CGI connectionPerl Training Australia (http://www.perltraining.com.au/)5

Chapter 2. What is CGI?A simple HTTP transaction, such as a request for a static HTML page, works as follows:1. The user types a URL into his or her browser, or specifies a web address by some other meanssuch as clicking on a link, choosing a bookmark, etc2. The user agent connects to port upon which the HTTP server is running (usually port 80)3. The user agent sends a request such as GET/index.html4. The user agent may also send other headers5. The HTTP server receives the request and finds the requested file in its filesystem6. The HTTP server sends back some HTTP headers, followed by the contents of the requested file7. The HTTP server closes the connectionWhen a user requests a CGI program, however, the process changes slightly:1. The user agent sends a request as above2. The HTTP server receives the request as above3. The HTTP server finds the requested CGI program in its file system4. The HTTP server executes the program5. The program produces output, including HTTP headers6. The HTTP server sends back the output of the program7. The HTTP server closes the connectionTerminologyDuring this course we’ll use a number of terms that have very specific meanings. A list of theseterms can be found in Appendix E.HTTP MethodsGETThe GET method means retrieve whatever information is identified by the request URI. If the requestURI refers to a data-producing process (eg a CGI program), it is the produced data which is returned,and not the source text of the process.HEADThe HEAD method is identical to GET except that the server will only return the headers, not thebody of the resource. The meta-information contained in the HTTP headers in response to a HEADrequest should be identical to the information sent in response to a GET request. This method can beused to obtain meta-information about the resource without transferring the body itself.6Perl Training Australia (http://www.perltraining.com.au/)

Chapter 2. What is CGI?POSTThe POST method is used to request that the server use the information encoded in the request URIand use it to modify a resource such as: Annotation of an existing resource Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles Providing data {such as the result of submitting a form} to a data-handling process Updating a databaseWhat is needed to run Perl CGI programs?There are several things you need in order to create and run Perl CGI programs. a web server web server configuration which gives you permission to run CGI a Perl interpreter appropriate Perl modules, such as CGI.pm a shell account is extremely useful but not essentialMost of the above requirements will need your system administrator or ISP to set them up for you.Some will be wary of allowing users to run CGI programs, and may require you t

Perl language. Perl 5 differs significantly from previous versions of Perl, so you will need a Perl 5 interpreter to use what you have learnt. However, older Perl programs should work fine under Perl 5. At the time of writing, the most recent stable release of Perl is version 5.6.1, however ol