Chapter 3. The Common Gateway Interface
Now that we have explored HTTP in general, we can return to our discussion of CGI and see how our scripts interact with HTTP servers to produce dynamic content. After you have read this chapter, you’ll understand how to write basic CGI scripts and fully understand all of our previous examples. Let’s get started by looking at a script now.
This script displays some basic information, including CGI and HTTP revisions used for this transaction and the name of the server software:
#!/usr/bin/perl -wT print <<END_OF_HTML; Content-type: text/html <HTML> <HEAD> <TITLE>About this Server</TITLE> </HEAD> <BODY> <H1>About this Server</H1> <HR> <PRE> Server Name: $ENV{SERVER_NAME} Listening on Port: $ENV{SERVER_PORT} Server Software: $ENV{SERVER_SOFTWARE} Server Protocol: $ENV{SERVER_PROTOCOL} CGI Version: $ENV{GATEWAY_INTERFACE} </PRE> <HR> </BODY> </HTML> END_OF_HTML
When you request the URL for this CGI script, it produces the output shown in Figure 3.1.
Figure 3-1. Output from server_info.cgi
This simple example demonstrates the basics about how scripts work with CGI:
The web server passes information to CGI scripts via environment variables, which the script accesses via the
%ENV
hash.CGI scripts produce output by printing an HTTP message on STDOUT.
CGI scripts do not need to output full HTTP headers. This script outputs only one HTTP header, Content-type ...
Get CGI Programming with Perl, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.