CGI Programming on the World Wide Web

Previous Chapter 3 Next
 

3.3 Accept Types and Content Types

CGI applications can return nearly any type of virtual document, as long as the client can handle it properly. It can return a plain text file, an HTML file ... or it can send PostScript, PDF, SGML, etc.

This is why the client sends a list of "accept types" it supports, both directly and indirectly through helper applications, to the server when it issues a request. The server stores this information in the environment variable HTTP_ACCEPT, and the CGI program can check this variable to ensure that it returns a file in a format the browser can handle.

It's also why when you are returning a document, the CGI program needs to use the Content-type header to notify the client what type of data it is sending, so that the browser can format and display the document properly.

Here's a simple snippet of code that checks to see if the browser accepts JPEG or GIF images:

#!/usr/local/bin/perl
$gif_image = "logo.gif";
$jpeg_image = "logo.jpg";
$plain_text = "logo.txt";
$accept_types = $ENV{'HTTP_ACCEPT'};
if ($accept_types =~ m|image/gif|) {
		$html_document = $gif_image;
} elsif ($accept_types =~ m|image/jpeg|) {
		$html_document = $jpeg_image;
} else {
		$html_document = $plain_text;
}
.
.
.

We use a regular expression to search the $accept_types variable for a MIME content type of image/gif and image/jpeg. Once that's done, you can open the file, read it, and output the data to standard output, like we've seen in previous examples.


Previous Home Next
CGI and Response Headers Book Index The Content-length Header