Web Perl   «Prev  Next»

Lesson 8Getting started with CGI
ObjectiveExplore the role of MIME headers in a CGI program.

How to get started with Perl and CGI

Because the process of running your first CGI program is complex enough in itself, we will first consider a simple CGI program that sends a brief message back to your browser before we pursue the added complexity of using forms. A CGI program sends its output back to the client as part of the response from the server.
Because this can be any sort of output that a Web client can handle, you need to first specify what sort of data you will be sending. Usually it will be HTML (just another Web page for all intents and purposes), but since it is possible to send anything, you will need to explicitly tell the client what you are sending.

MIME header

The first output from the CGI program is a MIME header that specifies what format the output is using.
Mime headers are explained on this page.
HTTP_ACCEPT: The formats accepted by the browser. This information is optionally supplied by the browser when it first requests the page from the server. In our example, the default types accepted include all of the major graphics types (GIF, JPEG, X bitmap), as well as all other MIME types (*/*).

Sending Information Back to the Browser

Communicating information back to the user is so simple, you will be looking for ways to make it more complicated. In essence, you print information to STDOUT, and this is then sent back verbatim to the browser. The actual method is more complex. When a web server responds with a static file, it returns an HTTP header that tells the browser about the file it is about to receive. The header includes information such as the content length, encoding, and so on. It then sends the actual document back to the browser. The two elements
  1. the header and
  2. the document
are separated by a single blank line. How the browser treats the document it receives is depends on the information supplied by the HTTP header and the extension of the file it receives. This allows you to send back a binary file (such as an image) directly from a script by telling the application what data format the file is encoded with. When using a CGI application, the HTTP header is not automatically attached to the output generated, so you have to generate this information yourself. This is the reason for the
print "Content-type: text/html\n\n";