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.
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
- the header and
- 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