After spending the past few months understanding Perl'svariables, operators and functions, it's time to start writing Perlprograms for the Web. This week, Perl 101 introduces you to the basics ofCGI scripting, and also teaches you how to use a new type of Perl variable,the hash.
You're probably wondering what all this has to do with anything, and why exactly we're torturing you with it at this stage in this series. Well, hashes come in very useful when writing CGI scripts that run off your Web server.and coincidentally, that's just what we're going to be talking about next.
Over the last couple of months, you've spent a great deal of effort understanding variables, loops, file input and output, and string manipulation. The goal of all this: to give you the confidence to use Perl to develop dynamic Web pages. And we're now at the point where you begin applying your hard-won knowledge to some real-life applications.
In non-geek terms, CGI, or the Common Gateway Interface, is a programming environment which allows you to communicate between Web pages and a Web server. So, when you submit a form on a Web site (for example), a CGI program on the server receives your information, saves it to a database or flat file, and dynamically generates an acknowledgment page. The form data is usually submitted is a series of name-value pairs (think hashes!) which is then interpreted and used by the CGI program.
Of course, CGI programs can do much more than this - you can run CGI programs to communicate with a database, read and write flat files, or run processes on the server.
Perl is by far the most common language used for CGI programs. If you're using Apache, you should have the ability to execute CGI scripts out of the box - although you need to keep the following points in mind:
* Your CGI script usually needs to be stored in a particular directory for it to work correctly. This directory is usually the /cgi-bin/ directory off your Web server, although you should check with your Webmaster or system administrator to make sure.
* CGI scripts need to be "mode-executable" under *NIX systems. Simply use the "chmod" command to give your scripts, and the directory they reside in, 0755 permission.
* Many Web servers require that your CGI script end in the file extension .cgi. Again, you'll need to check this with your system administrator.
* Since CGI scripts can run commands on the server, they pose an inherent security risk. You'd be well advised to check that your scripts do not open security holes on your system by running them past an experienced Webmaster before using them in a production environment. The examples we're going to be using are meant for demonstration purposes *only*.
* If you're going to process form data via a CGI script, make sure that your server supports both GET and POST methods of transferring data.
'nuff said. Let's actually write one of these babies.
This article copyright Melonfire 2000. All rights reserved.