Previous | Top | Next | Search | Comments

CGI programming

CREATING VALID HTML

Writing polite code.

The previous example was not very polite. In fact, it out and out lied about its content saying its data was HTML when it was plain text. The second example demonstrates how to conform a bit more to HTTP and HTML standards by including more information about the script's content and correctly formating the output. Try the following script, 02-validCoding.cgi:

Hello, World! #2

The script (below) has the exact functionality as the first example, but this one is more truthful about its output's content and it formats the results. View the source code of the output of Hello, World! and Hello, World! #2 to see the difference.

THE CODE

Here is the script's code:

#!/usr/local/bin/perl

# 02-validCoding.cgi
# This script demonstrates valid HTTP/HTML coding output.

# Eric Lease Morgan
# from Becoming a World Wide Web Server Expert
# http://sunsite.berkeley.edu/~emorgan/waves/
# 04/01/97 - renamed file as a .cgi
# 01/20/97 - Martin Luther King Day

# declare the MIME standard
$header  = "MIME-Version: 1.0\n";

# describe the MIME type
$header .= "Content-type: text/html\n";

# terminate the HTTP header
$header .= "\n";

# create an HTML file
$html    = "<html>\n";
$html   .= "<head>\n";
$html   .= "<title>\n";
$html   .= "Example #2 - Hello, World!\n";
$html   .= "</title>\n";
$html   .= "</head>\n";
$html   .= "<body>\n";
$html   .= "Hello, World!\n";
$html   .= "</body>\n";
$html   .= "</html>\n";

# output the header and html content
print "$header$html";

# exit gracefully
exit;                                    

HOW IT
WORKS

Here is how the script works:

  1. The first few lines of the script are comments. The first line is the script's wrapper. The next few lines provide some documentation.
  2. The next few lines build the HTTP header ($header) describing the MIME version and type that is being returned.
  3. Next, the variable $html is built including valid HTML tags.
  4. Then the variables representing the HTTP header and HTML data are returned with a print statement.
  5. Finally, the script quits with the exit statement.


Previous | Top | Next | Search | Comments

Version: 1.5
Last updated: 2004/12/23. See the release notes.
Author: Eric Lease Morgan (eric_morgan@infomotions.com)
URL: http://infomotions.com/musings/waves/