Home > Store

CGI Programming in C and Perl

Register your product to gain access to bonus material or receive a coupon.

CGI Programming in C and Perl

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 1996
  • Dimensions: 7-3/8" x 9-1/8"
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-42219-0
  • ISBN-13: 978-0-201-42219-1

The simple, static hypertext documents that currently dominate the Web canconvey a great deal of information, but eventually their limitations becomeclear. What if you wish to provide dynamic data--information that changes overtime? What if you want to sell products on your Web site and secure paymentinformation from users? Or what if you seek to provide a search facility thatpermits a Web database to be explored? Dynamic resources of this sort areaccomplished through CGI (Common Gateway Interface) programming.

CGI programs can take advantage of any resource available to the servercomputer to generate their output and can also accept input from the userthrough forms. These two basic capabilities have led to a wide variety ofapplications, such as forms processing, generation of inline images and movies,the formatting of data sets based on queries to a database, real-time updatesto Web pages, and more.

CGI Programming in C and Perl shows you how to create theseinteractive, multimedia documents via CGI programming in two practicallanguages: C, which has distinct performance advantages, and Perl, one of themost popular for CGI today. Applications and source code are presented in both languages.

You'll learn how to:

  • generate HTML pages and images on the fly

  • get CGI access on your ISP's site

  • ensure security for your CGI-activated site

  • parse form submissions directly

  • send e-mail via forms and CGI.



0201422190B04062001

Downloads

Supplements

The CGI Standard

The CGI standard is intended to provide a consistent interface between Web servers and programs that extend their capabilities. As discussed in Chapter 2, Web servers are able to deliver static documents from files without the assistance of other programs. However, dynamic content, database interfaces, and responsiveness to user input are all desirable and cannot be accomplished by static documents alone.

This chapter gives an overview of the CGI standard, examining both its definition and its reasons for existence. Topics introduced in this chapter are covered in more detail and with full examples in later chapters. So keep this in mind if you find portions of the chapter difficult to follow.

The Need for a Standard

Dynamic documents have been around almost as long as the Web itself. From the first days of the Web, programmers have found ways to generate Web pages on the fly. Early systems of this sort often involved custom servers--servers developed solely to deliver a particular type of dynamic content. The simplicity of the original HTTP1 (HyperText Transfer Protocol) specification made this approach practical, and it is sometimes still employed today when efficiency is of paramount concern.

As Web servers gained in sophistication, it soon became apparent that it was not practical to replicate the advanced security, logging, communications, and load-management features of a modern server for every application that required dynamic documents. So Web server developers began to provide interfaces through which external programs could be executed, usually in response to a request for a document in a designated portion of the document tree. The NCSA httpd (HTTP daemon) was the first Web server to provide such an interface.2

These first external-program interfaces represented a significant advance but did not solve the standardization problem. The various Web servers followed separate standards for the development of external programs, so it was impossible to write a single external program that would be useful with all servers.

The Goals of CGI

The CGI standard was developed jointly by NCSA (the National Center for Supercomputing Applications) and CERN (the European Laboratory for Particle Physics) in response to the need for a consistent external-program interface.3 In addition to a consistent, standard interface, the CGI standard seeks to provide reasonable guarantees that user input, particularly form submissions, will not be lost due to the limitations of the server operating system. The CGI standard also attempts to provide the external program with as much information as possible about the server and the browser, in addition to any information that may be known about the user. Finally, the CGI standard attempts to be straightforward so as to make the development of simple CGI applications easy.

Largely, the CGI standard has achieved these goals. Other emerging approaches are sometimes more efficient, especially when tuned to specific operating systems (see Chapter 15, "What's Next: CGI and Beyond"), but the portability and simplicity of the CGI standard has led to its widespread use.

CGI does not always achieve its goal of simplicity. The parsing of form data is somewhat complex, especially when done properly and thoroughly. However, its popularity has led to the development of several freely available tools to simplify the task of CGI programming, including several Perl libraries and the cgic library for C (see Chapter 8).

CGI and the HyperText Transfer Protocol

The server executes CGI programs in order to satisfy particular requests from the browser. The browser then expresses its requests using the HyperText Transfer Protocol.1 The server responds by delivering either a document, an error status code, and/or a redirection to a new URL according to the rules of that protocol. While CGI programs usually need not speak the HTTP directly, certain aspects of it are important to CGI.

HTTP requests can be of several types, which are called methods. For CGI programmers, the most important are GET and POST.

The GET method is used to request a document and does not normally submit other input from the user. If the requested URL points to a CGI program, the CGI program generates either a new document, an error code, or a redirection to another document (see "CGI Standard Output" later in this chapter). The CGI program can identify this situation by examining the REQUEST_METHOD environment variable, which in this case will contain the string GET.

In some cases, there is a certain amount of user input, which the browser submits as part of the URL. This may happen for example when the <ISINDEX> HTML tag is used or an HTML form delivers its data via the GET method. This information will then be stored in the QUERY_STRING environment variable. This approach is rather unwieldy and so should be avoided in new CGI programs.

The POST method is used to deliver information from the browser to the server. In most cases, the information sent is a form submission. The CGI program then reads the submitted information from standard input (see "CGI Standard Input" later in this chapter for the format of the data). In this case, the REQUEST_METHOD environment variable will be set to the string POST. To be certain the posted information is a form submission, the CGI prgram examines the CONTENT_TYPE environment variable to make sure it contains the string x-www-form-urlencoded. The latest Web browsers can also post other forms of data to the Web server.

After examining the submission, the program typically generates either a new document, an error code, or a redirection to another URL (see "CGI Standard Output" later in this chapter).

Other methods, such as PUT, are coming into use, but GET and POST remain the most important HTTP methods for CGI programming.

CGI Environment Variables

The HTTP daemon (server) shares a variety of information with the CGI program. This information is communicated in the form of environment variables.

In C, environment variables are normally accessed using the getenv() function. For example, the following code example retrieves the PATH_INFO environment variable. This variable contains any additional information in the URL of the user's request beyond the path of the CGI program itself and preceding a question mark, if any:

char *serverName;

serverName = getenv("PATH_INFO");

In Perl, environment variables are found in the %ENV associative array. The following Perl expression also refers to the PATH_INFO environment variable:

$serverName = $ENV{'PATH_INFO'} ;

Appendix 1 contains a complete list of the CGI environment variables. The most important are introduced as they are used in the next several chapters.

CGI Standard Output

CGI programs are normally expected to output one of three things: a valid Web document, a status code, or a redirection to another URL.

Outputting a New Document

To output a new document, a CGI program must first indicate the type of data contained in the document. For instance, the following content type header indicates that the data that follows is in HTML:

Content-type: text/html

VERY IMPORTANT: TWO line breaks must follow the Content-type line. Otherwise, your document will be ignored. A blank line signals the end of the headers and the beginning of the document, if any.

Following the content type header, the CGI program can output any valid HTML document. Many examples of HTML documents are in this book, beginning in Chapter 4.

Information about other content types, such as image/gif, is presented in Chapter 10 and Appendix 2.

Returning a Status Code

If an error occurs, the CGI program may wish to output a status code rather than a document. In this case, the following MIME header whould be output:

Status: #### Status Message

where #### is replaced with any valid HTTP status code4 and Error Message with an explanatory message for the user.

IMPORTANT: The status line must be followed by two line breaks. Otherwise, the status code will be ignored.

No further output is necessary.

Redirecting the Browser to Another URL

It is not uncommon for a programmer to decide that a request is best handled by redirecting the user to another URL. The other URL can be on the same or another system. In the first case, the server will usually intervene and attempt to resolve the request without sending the redirection back to the browser. In the second case, the new URL is transmitted back to the browser, which then makes a connection to a new server.

To redirect the browser to another URL, output the following header:

Location: URL

where URL is replaced with any valid URL. If the URL refers to a document on the same server, http://hostname can be omitted, and performance gains are realized by doing so. To ensure compatibility with all servers, you are advised to begin such local URLs from the document root (begin with a / character). Note: Some browsers also require the header URI:URL... in addition to Location:URL... .

IMPORTANT: The status line must be followed by TWO line breaks. Otherwise, the redirection will be ignored.

No further output is necessary. More information about this subject is presented in Chapter 12.

Perl and C code to handle output from CGI programs is presented throughout this book beginning in Chapter 4.

CGI Standard Input

Earlier external-program standards specified form data to be stored entirely in environment variables or passed on the command line, an approach that risks truncation under some operating systems when the amount of information is too great. While the CGI standard allows this approach, it also allows and encourages an approach in which the form data is passed to the external program as its standard input, meaning the data can be accessed with simple standard I/O calls such as the C functions getc() and fread().

When no data has been submitted by the user or a form has been submitted with the GET method, standard input will contain no information. However, when data has been sent by the user using the POST method, the data will appear at standard input. Use of the POST method is the preferred method for form submissions. The format for form data is:

keyword=value&keyword=value&keyword=value

that is, a stream of keyword and value pairs, where keywords and values are separated by equal signs and pairs by & signs.

IMPORTANT: Note that all characters that are escaped in URLs are also escaped in posted form data. That is, if characters such as &, =, and % are typed by the user and submitted as part of the request, they will appear escaped in standard input as follows:

%xx

where the ASCII value of the character in hex is substituted for xx. For instance, the %, ASCII value 37 decimal, 21 hexadecimal, appears as follows:

%21

The CONTENT_LENGTH environment variable will always contain the total number of characters of data to be read from standard input.

Perl and C code to handle the CGI standard input stream is presented in Chapter 7, "Handling User Input: Interacting with Forms."

Conclusion

In this chapter, I introduced the basic concepts of CGI. In Chapter 3, we begin writing CGI programs.

References

1. W3 Consortium, "HyperText Transfer Protocol Specification."
[URL:http://www.w3.org/hypertext/WWW/Protocols/Overview.html]

2. NCSA HTTPd Development Team, "Upgrading NCSA httpd."
[URL:http://hoohoo.ncsa.uiuc.edu/docs/Upgrade.html]

3. W3 Consortium, "Overview of CGI."
[URL:http://www.w3.org/hypertext/WWW/CGI/Overview.html]

CD Contents

Untitled Document Download the CD Contents from the book CGI Programming in C and Perl

Sample Content

Table of Contents

(Each chapter ends with a Conclusion.)

Acknowledgments.


1. World Wide Web Documents.

The Universe of Web Documents.

References.



2. The CGI Standard.

The Need for a Standard.

The Goals of CGI.

CGI and the HyperText Transfer Protocol.

CGI Environment Variables.

CGI Standard Output.

CGI Standard Input.

References.



3. Obtaining CGI Access.

Purchasing CGI Access on a Commercial Server.

Common Rules for Installing CGI Programs.

Creating Your Own Internet Site.

Configuring Web Servers to Recognize CGI Programs.

References.



4. Some Simple CGI Examples.

Hello: Sending HTML to the Browser.

Leveraging Existing Programs: cuptime.



5. Virtual Directory Spaces: Taking Advantage of PATH_INFO.

What Are Environment Variables?

Using PATH_INFO: Creating a Virtual Document Space.

The World Birthday Web, Part I: Browsing Birthdays.

When PATH_INFO Isn’t Enough.

References.



6. Identifying the User: More CGI Environment Variables.

More Environment Variables.

REMOTE_IDENT: The Pitfalls of User Identification.

AUTH_TYPE and REMOTE_USER: Identifying the User on Your Own Terms.

Applications of REMOTE_USER.

References.



7. Handling User Input: Interacting with Forms.

Creating Forms.

Processing Form Input.

Accepting Comments.

Existing Comment-form and Guestbook Packages.

References.



8. Using cgic and cgi-lib: Complete CGI Solutions.

The cgic Library: A Better API for CGI.

The World Birthday Web, Part II: Using cgic.

cgi-lib: Simplifying CGI for Perl Programmers.

The World Birthday Web, Part III: Using cgi-lib.



9. Sending E-mail from CGI Programs.

Alternatives to Using CGI.

Security Risks of Sending E-mail with /bin/mail.

Sending E-mail with sendmail.

Identifying the Sender: How Much Can Be Done?

A Complete E-mail Form: Accepting Bug Reports.

Existing CGI E-mail Packages.

References.



10. Multimedia: Generating Images in Dynamic Documents.

Pointing to Existing Images in a CGI-generated HTML Page.

Generating Dynamic Images: Mime Types and Multimedia.

A CGI Program That Delivers an Image Instead of HTML.

Off-the-shelf Ways to Generate Images.

Using the gd Graphics Library.

Drawing Graphs on the Fly.

References.



11. Advanced Forms: Using All the Gadgets.

New Tricks with Text Elements.

A Complete Example.



12. Advanced CGI and HTML Features.

A Problem: Sending Updated Information to the User.

Client Pull: Web Pages That Update Themselves.

Server Push: Pushing the Limitations.

Making Decisions Based on Browser Type.

Implementing Imagemaps.

Redirection: Forwarding Requests to Another URL.

Using capture: Debugging CGI Programs in Real Debuggers.

References.



13. The Solar System Simulator: Pushing the Limitations of CGI.

Is CGI the Right Way to Do This?

Designing the SSS: Overcoming CGI Limitations.

Perl Notes.

The SSS in C: nph-sss.c.

The SSS in Perl: nph-sss.



14. World Wide Web Wall Street: An Advanced CGI Application.

The Security Problem.

The Design of WWWWS.

Simulating Stock Prices in C: simtrade.c.

Simulating Stock Prices in Perl: simtrade.

Installing and Using simtrade.

The trade Program: Interacting with the User.



15. What’s Next: CGI and Beyond.

For Some Tasks, CGI is Overkill.

Improved APIs: Faster Replacements for CGI.

The Fundamental Limitation of CGI.

Addressing CGI Limitations: Web Browser Programming Tools.

Why CGI Isn’t Going Away Any Time Soon.

References.



Appendix 1. CGI Environment Variables.


Appendix 2. Internet Media Content Types.


Appendix 3. cgic Reference Manual.


Appendix 4. gd Reference Manual.



Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020