next up previous contents
Next: CGI and Environment Variables Up: CGI Programming in Perl Previous: Why Are File Permissions

HTTP Headers

The first line of output for most CGI programs must be an HTTP header that tells the client Web browser what type of output it is sending back via STDOUT. Only scripts that are called from a server-side include are exempt from this requirement.

  Format       Content-Type    
HTML text/html
Text text/plain
Gif image/gif
JPEG image/jpeg
Postscript application/
   postscript
MPEG video/mpeg
Redirection to another Web page Location: http://www.foobar.com
Cookie Set-cookie: ...Error MessageStatus: 402
Error Message Status: 402

All HTTP headers must be followed by a blank line. Use the following line of code as a template:

 
print("Content Type: text/html\n\n");

Notice that the HTTP header is followed by two newline characters. This is very important. It ensures that a blank line will always follow the HTTP header.

If you have installed any helper applications for Netscape or are familiar with MIME types, you already recognize the text/plain and text/html parts of the Content Type header. They tell the remote Web browser what type of information you are sending. The two most common MIME types to use are text/plain and text/html.

The Location header is used to redirect the client Web browser to another Web page. For example, let's say that your CGI script is designed to randomly choose from among 10 different URLs in order to determine the next Web page to display. Once the new Web page is chosen, your program outputs it like this:

print("Location: $nextPage\n\n");

Once the Location header has been printed, nothing else should be printed. That is all the information that the client Web browser needs.

Cookies and the Set-cookie: header are discussed in the "Cookies" section later in this chapter.

The last type of HTTP header is the Status header. This header should be sent when an error arises in your script that your program is not equipped to handle. I feel that this HTTP header should not be used unless you are under severe time pressure to complete a project. You should try to create your own error handling routines that display a full Web page that explains the error that happened and what the user can do to fix or circumvent it. You might include the time, date, type of error, contact names and phone numbers, and any other information that might be useful to the user. Relying on the standard error messages of the Web server and browser will make your Web site less user friendly.



 
next up previous contents
Next: CGI and Environment Variables Up: CGI Programming in Perl Previous: Why Are File Permissions
dave@cs.cf.ac.uk