CGI Programming with Perl

28 downloads 126707 Views 231KB Size Report
CGI Programming with Perl. #!/usr/bin/perl. # It Came From the Crypt! $q= q&9RM . 8 ba1c. HtJprcG. 6SJ3dk ... This is version 4.1 of Perl Training Australia's "Perl Programming with CGI" training manual. ...... C. ASCII Pronunciation Guide .
CGI Programming with Perl #!/usr/bin/perl # It Came From the Crypt!

$q= q&9RM 8 ba1c HtJprcG 6SJ3dk aQM 8 p j p8vsY i3UnT f kcRJk9w xW2v h2GVK3 YL1gNvf YEX dBQdE TIdpMu WD9Y CAvK0 BrsuKn9kXUwk aNpj8q ISZgRZkUg2I8W9jJsG8Rg9yeE8LvqZR7A Ho PDIRVAVCgafA9MZjFb31Ea5bqr7gCg X zPpgkPsHjTP8iC2TtVYE0PUR b z Y b3 EQiZrZiIm6Nc81WY qs U g 7m QzHM2VjY62II5Bg 7N e k kt 7 5JLD86&;$u=$q =~ s & \s &&xg&&−2;@v= unpack q &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} &&$y ne "y"?$y: $l{$y} ;$i=~ s+$&+ +x }$y=~m &ymum ~ my&

Kirrily Robert Paul Fenwick Jacinta Richardson

CGI Programming with Perl by Kirrily Robert, Paul Fenwick, and Jacinta Richardson Copyright © 1999-2000 by Netizen Pty Ltd Copyright © 2000 by Kirrily Robert Copyright © 2001 by Obsidian Consulting Group Pty Ltd Copyright © 2001-2004 by Paul Fenwick Copyright © 2001-2004 by Jacinta Richardson Copyright © 2001-2004 by Perl Training Australia Open Publications License 1.0 Cover 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 latest version 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 from the copyright holder. This document is a greatly revised and edited copy of the training notes originally created by Kirrily Robert and Netizen Pty Ltd. These revisions were made by Paul Fenwick and Jacinta Richardson. Copies of the original training manuals can be found at http://sourceforge.net/projets/spork Copies of the Obsidian training manuals can be found at http://www.obsidian.com.au/training This training manual is maintained by Perl Training Australia, and can be found at http://www.perltraining.com.au/notes.html This is version 4.1 of Perl Training Australia’s "Perl Programming with CGI" training manual.

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

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

v

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

vi

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

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

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

vii

viii

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

List of Tables 4-1. FORM element attributes ............................................................................................................ 21 4-2. CGI.pm FORM defaults .............................................................................................................. 22 A-1. Simple Unix commands ............................................................................................................. 51 B-1. Layout of editor cheat sheets ...................................................................................................... 53 C-1. ASCII Pronunciation Guide........................................................................................................ 55 D-1. Basic HTML elements................................................................................................................ 57 E-1. HTTP status codes ...................................................................................................................... 60

List of Figures 2-1. A typical HTTP and CGI connection ............................................................................................ 5

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

ix

x

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

Chapter 1. Introduction Welcome to Perl Training Australia’s CGI Programming with Perl training course. This is a one-day course in which you will learn how to write dynamic, interactive web applications using the Perl programming 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::Template

Assumed knowledge It 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 regular expressions



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 editor command summary in Appendix B. The Unix operating system commands you will need are mentioned and explained very briefly throughout the course - please feel free to ask if you need more help. The required Perl knowledge was covered in our "Introduction to Perl" course. If you’ve worked with Perl for about a year you’ll know much of the required material. Lastly, an HTML cheat-sheet is provided in Appendix D for those 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 programming

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

1

Chapter 1. Introduction

Platform and version details This module is taught using Unix or a Unix-like operating system. Most of what is learnt will work equally well on Windows NT or other operating systems; your instructor will inform you throughout the course of any areas which differ. All Perl Training Australia’s Perl training courses use Perl 5, the most recent major release of the 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 older versions of Perl 5 are still common. Your instructor will inform you of any features which may not exist in older versions. The web server used for examples in this module is Apache (http://www.apache.org). We have chosen this web server for examples as it is freely available, widely used, and very fast and full-featured.

The course notes These course notes contain material which will guide you through the topics listed above, as well as appendices containing other useful information. The following typographic conventions are used in these notes: System commands appear in this typeface Literal text which you should type in to the command line or editor appears as monospaced

font.

Keystrokes which you should type appear like this: ENTER. Combinations of keys appear like this: CTRL-D Program listings and other literal listings of what appears on the screen appear in a monospaced font like this.

Parts of commands or other literal text which should be replaced by your own specific values appears like this

Notes and tips appear offset from the text like this.

Notes which are marked "Advanced" are for those who are racing ahead or who already have some knowledge of the topic at hand. The information contained in these notes is not essential to your understanding of the topic, but may be of interest to those who want to extend their knowledge.

Notes marked with "Readme" are pointers to more information which can be found in your textbook or in online documentation such as manual pages or websites.

2

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

Chapter 1. Introduction

Notes marked "Caution" contain details of unexpected behaviour or traps for the unwary.

Other materials In addition to these notes, it is highly recommend that you obtain a copy of Programming Perl (2nd or 3rd edition) by Larry Wall, et al., more commonly referred to as "the Camel book". While these notes have been developed to be useful in their own right, the Camel book covers an extensive range of topics not covered in this course, and discusses the concepts covered in these notes in much more detail. The Camel Book is considered to be the definitive reference book for the Perl programming language. The page references in these notes refer to the 3rd edition of the camel book. References to the 2nd edition will be shown in parentheses.

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

3

Chapter 1. Introduction

4

Perl 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 dynamic and interactive material. We explore the Hypertext Transfer Protocol as it applies to both static and CGI-generated content, and examine raw HTTP requests and responses by telnetting to a web server.

Definition of CGI CGI is the Common Gateway Interface, a standard for programs to interface with information servers such as HTTP (web) servers. CGI allows the HTTP server to run an executable program or script in response to a user request, and generate output on the fly. This allows web developers to create dynamic and interactive web pages. CGI programs can be written in any language. Perl is a very common language for CGI programming as it is largely platform independent and the language’s features make it very easy to write powerful applications. 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 program which can be written in any language.

Introduction to HTTP To 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 for transferring 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 a basic understanding of CGI programming. An HTTP cheat-sheet, containing some common terminology and a table of status codes, appears in Appendix E.

RFCs, or "Request For Comment" documents, can be obtained from the Internet Engineering Task Force (IETF) website (http://www.ietf.org/) or from mirrors such as The RFC mirror at AARNet (http://mirror.aarnet.edu.au/pub/rfc).

Figure 2-1. A typical HTTP and CGI connection

Perl 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 means such as clicking on a link, choosing a bookmark, etc 2. 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.html

4. The user agent may also send other headers 5. The HTTP server receives the request and finds the requested file in its filesystem 6. The HTTP server sends back some HTTP headers, followed by the contents of the requested file 7. The HTTP server closes the connection When a user requests a CGI program, however, the process changes slightly: 1. The user agent sends a request as above 2. The HTTP server receives the request as above 3. The HTTP server finds the requested CGI program in its file system 4. The HTTP server executes the program 5. The program produces output, including HTTP headers 6. The HTTP server sends back the output of the program 7. The HTTP server closes the connection

Terminology During this course we’ll use a number of terms that have very specific meanings. A list of these terms can be found in Appendix E.

HTTP Methods GET The GET method means retrieve whatever information is identified by the request URI. If the request URI 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.

HEAD The HEAD method is identical to GET except that the server will only return the headers, not the body of the resource. The meta-information contained in the HTTP headers in response to a HEAD request should be identical to the information sent in response to a GET request. This method can be used to obtain meta-information about the resource without transferring the body itself.

6

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

Chapter 2. What is CGI?

POST The POST method is used to request that the server use the information encoded in the request URI and 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 database

What 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 essential

Most 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 to obey certain security regulations or pay extra for the privilege.

Chapter summary •

CGI stands for Common Gateway Interface



HTTP stands for Hypertext Transfer Protocol. This is the protocol used for transferring documents and other files via the World Wide Web.



HTTP clients (web browsers) send requests to HTTP (web) servers, which are answered with HTTP responses



The request/response can be examined by telnetting to the appropriate port of a web server and typing in requests by hand.

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

7

Chapter 2. What is CGI?

8

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

Chapter 3. Generating web pages with Perl In this chapter... In this section, we will create a simple "Hello world" CGI program and run it, then extend upon that to integrate parts of Perl taught in previous modules. Alternative quoting mechanisms are briefly covered, and we also discuss debugging techniques for CGI programs.

Your public_html directory The training server has been set up so that each user has their own web space underneath their home directory. All files which will be accessible via the web should be placed in the directory named public_html. This is common for most personal homepages. The directory ~username/public_html on the Unix file system maps to the URL http://hostname/ via the web.

~username/

Replace username with your username. Your instructor will tell you what the hostname is.

The CGI directory CGI scripts are usually kept in a separate directory from plain HTML files. This directory is most commonly called cgi-bin (the "bin" stands for "binary" but really just means "executable files", whether compiled binaries or interpreted scripts such as Perl programs). The web server is usually set up so that you only have permission to run CGI programs from the cgi-bin directory, for security reasons. Before proceeding any further, do the following: 1. Change to your public_html directory 2. If you type ls to get a directory listing, you will see that you have several HTML files here, as well as a cgi-bin directory. 3. Change to your cgi-bin directory and type ls, and you will see that the example scripts for this course are already installed here. If you were setting this up for yourself, you would need to be sure of the following: 1. That your home directory is world executable 2. That your public_html directory is world executable 3. That all your HTML files are world readable 4. That your cgi-bin directory is world executable - note that it is not compulsory to have a cgi-bin directory - some server configurations allow you to execute a CGI script from any directory. Some servers won’t let you execute CGI scripts at all. 5. That all your CGI scripts are world readable and executable

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

9

Chapter 3. Generating web pages with Perl

CGI.pm. Making CGI programming a breeze. The CGI.pm library has been created to make a number of otherwise painful tasks easy. Using the CGI.pm library saves you from having to remember what HTTP headers look like, or which ones you have to set to stop your output being cached. It saves you from having to worry about how to generate or read cookies. It saves you from having to parse stuff to work out the users current URL. Most importantly saves you from having to worry about how to get to any the parameters passed to your script. Not only does the CGI.pm library do all these nice things, it also gives you a functional interface to the HTML tags.

For those who’ve forgotten any HTML that they ever knew, don’t start imagining that the code below is using Perl’s readline() () operator. That’s just how HTML tags are written.

For example, instead of writing: print "Content-type: text/html\n\n"; print qq{ Hello World Hello World };

You could write: use CGI qw/:standard/; print header, start_html({-title=>"Hello World", -bgcolor=>"#FFFFFF"}), "Hello World", end_html;

Which, I’m sure you’ll agree looks nicer, and saves you from having to remember all those HTML tags. (Later we’ll talk about another module that you can use to remove almost all of of the HTML from your programs altogether).

That header thing Now, we’ve jumped ahead a little here. What does that line print "Content-type: text/html\n\n";

do for us? That’s the HTTP header. Every CGI script must output a HTTP header giving a MIME content type, such as Content-type: text/html, with a blank line after it. Most of you have probably realised that the line in the second example: print header,

10

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

Chapter 3. Generating web pages with Perl does the same thing. However, it’s much easier to remember. The header function can also take arguments such as cookies and page expiry dates. We’ll cover cookies soon.

If your output is of another MIME type, you should print out the appropriate Content-type: header - for instance, a CGI program which outputs a random GIF image would use Content-type: image/gif. Of course, since you’ll be using CGI.pm you only need to write print header(’image/gif’);.

Quoting and roll-your-own quotes For those unacquainted with qq{}, this is another form of quoting strings in Perl. qq stands for double quotes, the same idea works with q for single quotes and qx for backticks. Note that the same rules apply for each of these quoting styles as for their more common equivalents: qq allows variable interpolation whereas q does not. Quoting things with qx will send them to the shell for execution. You may use any non-whitespace, non-alphanumeric character as your delimiters, pick the one least likely to appear in your string. Note that things that look like they should match up do. So ( matches ), { matches }, < matches > etcetera. There are some illustrated below. print print print print

qq(Jamie qq!Jamie qq[Jamie qq#Jamie

said said said said

"You should always watch your quotes!"\n); "These are Paul’s favourite quotes". (He was wrong).\n!; "Perl programs ought to start with #!"\n]; "My favourite regexp is ’/[jamie]*/i;’"\n#;

Using CGI.pm should save you from having to worry too much about quoting text too often, but it’s still bound to come up. While we’re here we’ll briefly mention HERE documents. These can sometimes be confusing for the reader, and usually pick-your-own-quotes will be clearer and do a better job. We cover them here for the sake of completeness, and because they are still very common in older code. HERE documents allow you to print text up unto a certain marking string. For example: print new(); print $cgi->start_ul; foreach my $name (qw/Jacob Jeremy Jacinta Jenni Jack/) { print $cgi->li($name); } print $cgi->end_ul;

This saves you from having to worry about importing start and end tags explicitly for every single HTML function you might want to use (start_form, end_form, start_table, end_table...). It’s also great for the purists out there who want complete control of their name space1. On the other hand, you have to make sure that the CGI object is available where ever you want to use its functions. We use the functional notation throughout the course because the object-oriented style can make the code look very cluttered, and this can detract from its readability.

Faking tags with CGI.pm In the previous section we mentioned that CGI would pretend to have functions for any tag you felt like creating. This is true. If you want to know how it works, ask your instructor in the next break. This means that if the W3C announced a new tag: (with it’s close tag ) you can go straight into writing that into your CGI programs. You’d just write: use CGI qw/:standard fish/; print fish("My something here");

and everything would work fine (if your browser implemented fish tags).

If you use the CGI.pm module in an Object Oriented manner here, you do not need to import or any other functions. You’re CGI object will be able to fake it for you anyway.

fish

use CGI; my $cgi = CGI->new(); print $cgi->fish("My something here");

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

13

Chapter 3. Generating web pages with Perl

Then again, why bother? (CGI D.W.I.M) If you are still having doubts as to why a functional interface to HTML tags is a good thing, especially when you can just print out the HTML yourself, this section is for you. Lets just imagine that you have the following code: use CGI qw/:standard/; print qq{}; print br; print textfield({-name=>"name", -value=>$name});

This should print out two input text fields, both called name, both initially containing the value of the $name variable. But lets just pretend for a moment that $name has quotation marks and a > character in it (amongst other things): $name = qq{Simon ">\nClick here!

This is best seen by seeing how your browser interprets this. (This code is in public_html/cgi-bin/whycgi.cgi.) What’s happened is that CGI.pm has escaped the HTML in the variable for you, saving you from having to worry. Perl knows that this is what you mean. It can’t do this for you in the literal HTML string because it does not know that what you are printing there is HTML. It’s just a string. By default CGI.pm will always escape HTML in the strings passed to any of its functions before printing them. Should you ever want to escape a string yourself CGI.pm provides a function called, intuitively enough escapeHTML.

CGI.pm has it’s limits. If you do something like the following: print start_h2; foreach my $header (@headers) { print $header, " "; } print end_h2;

the contents of each $header will not be escaped. This is because this is not called within a CGI.pm function. This is a good place to call escapeHTML. Mind you, here would probably be a good time to do something like: print h2("@headers");

which would escape the lot, but sometimes it’s not that easy.

14

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

Chapter 3. Generating web pages with Perl

Running your CGI program The simplest way to run your CGI program is to point your browser at it. In today’s case you can see your copy of hello.cgi at http://hostname/~username/cgi-bin/hello.cgi where hostname is the hostname of the web server and username is your login name.

The most common mistake new CGI programmers make is to forget to set the permissions correctly on their programs. CGI scripts must be world readable and executable. The second most common mistake is to print out something (anything) before printing out the header. Try to watch out for these.

Exercises Look forward to the next section if you encounter too many difficulties getting this to run 1. Look at the output of the hello.cgi and hello2.cgi programs with your browser. 2. Modify hello2.cgi to set a variable $name and include that name in the greeting. 3. Run your modified hello2.cgi script from the command line to ensure that it runs. (hit CTRL-d when your program pauses for input). 4. Now view your modified hello2.cgi script in your browser to see if your modifications worked correctly.

Debugging your CGI programs When writing CGI programs, there are many problems which may affect their execution. Since these will not always be easily understood by examining the web browser output, there are other ways to determine what’s going wrong. If there seems to be a problem first try the following steps: 1. Check that your program compiles by using perl

-c

2. Check the permissions on your cgi program. If it is not world executable then it won’t work. 3. Run your program on the command line. When your program waits for input, this is your opportunity to pass in parameters. For the moment, press CTRL-d. 4. If your program runs fine on the command line but still does not output to the browser, make sure that you have not forgotten to print the header before any other output. 5. Check the HTML source that you’re printing. Make sure that you’ve closed any tables you’ve opened and not made any obvious HTML errors. 6. Check the web server’s log files. The location of these vary from system to system. On our system they’re in /var/log/apache/.

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

15

Chapter 3. Generating web pages with Perl

Failing gracefully with CGI::Carp The errors given in the web server’s error logs are not always easy to read and understand. To make life easier, we can use a Perl module called CGI::Carp to add timestamps and other handy information to the logs. use CGI::Carp;

We can also make our errors go to a separate log, by using the carpout part of the module. This needs to be done inside a BEGIN block in order to catch compiler errors as well as ones which occur at the interpretation stage. BEGIN { use CGI::Carp qw(carpout); open(LOG, ">>cgi-logs/mycgi-log") || die("Unable to open mycgi-log: $!\n"); carpout(\*LOG); }

Lastly, and often the most useful use, we can cause any fatal errors to have their error messages and diagnostic information output directly to the browser: use CGI::Carp ’fatalsToBrowser’;

You can read all about CGI::Carp by checking out perldoc CGI::Carp. It’s also covered briefly on page 878 of the Camel book (but not in 2nd Ed.).

Exercises The following exercises practice using CGI to output different Perl data types such as arrays and hashes. Try using the CGI modules mentioned above. If you need help with HTML, there’s a cheat sheet in Appendix D. 1. Write a CGI program which creates an array then outputs the items in an unordered list (HTML’s