Chapter 20

CGI and VBScript

by Ramesh Chandak


CONTENTS

The very first Web pages lacked interactivity. Users could only browse through them and use hyperlinks to jump from one page to another. Common Gateway Interface (CGI) is one of several ways you can use to add interactivity to your Web pages. Other methods include using Java, JavaScript, VBScript, ActiveX, and plug-ins.

CGI represents a simple protocol of communication between the Web forms and the programs that reside on the Web server. A CGI script or program gets its input from the Web forms, processes it, and sends the results back to your browser. CGI is not a programming language; it is a script or a program that resides on the server. You can create a CGI script or program using almost any programming language, such as C/C++, Visual Basic, Perl, FORTRAN, or AppleScript, that supports standard input and output processing. This chapter introduces you to the concept of CGI, discusses why CGI was invented, and explains the different CGI environment variables. It also discusses the basic architecture of a CGI-based Web application and how data is communicated in such an architecture. This chapter further discusses the process of building a CGI application and how you can use VBScript to perform certain processing on the client side thus eliminating the need for CGI scripts or programs for some common tasks.

The CGI programs should process data and respond quickly. Remember, CGI programs get their input from the Web forms. The user is awaiting response while the data is being processed. Therefore, the CGI programs must respond quickly. Because the CGI programs reside on the server, you benefit from the server's processing power.

Early on during the design of your project consider the following two points:

Understanding CGI

The best way to understand CGI and what it does comes from examples. The following example demonstrates the results obtained using CGI and without CGI. In this example, an order form is created and placed online to enable customers to order products from anywhere in the world.

Listing 20.1 shows the HTML code that uses the mailto: command to send the order information from the browser to the Web server when the customer clicks the Send button.

The company, product, and price information included in Listing 20.1 is fictitious and exists for demonstration purposes. Notice the following line in Listing 20.1:


<FORM method=POST  ACTION="mailto:xyz@rksoftware.com">

The preceding line indicates to the browser the information being sent to the specified e-mail address when the user clicks the Send button using the mailto: command.

Figure 20.1 shows part of the HTML page resulting from Listing 20.1.

Figure 20.1 : HTML page created using Listing 20.2's code.


Listing 20.1. HTML sample using the mailto: command for ordering software.

<html>

<head>

<title>Order Desk 



</title>

</head>

<BODY background="wrbgrnd6.gif" 

bgproperties="fixed">

<center>

<h1>   Order Desk <a href="ita.html">

<img border=0 align="middle" src="itlogo2f.gif" alt="RK Software logo"></a> 

<img src="amex.gif"> <img src="mastercd.gif">  <img src="visacard.gif">

</h1>

<br><a href="order.html"><img src="ordpgbu7.gif" align="middle" 

alt="Go to DOWNLOADABLES Order Form" border=0></a> . 

<a href="customer_service.html"><img src="custsbut.gif" 

border=0 align="middle" alt="Customer Servie / FAQ">

</a>

</center>

<hr>

<br><b>USE OF THIS FORM</B>

<br>

<br>

This page is for ordering software on <b>diskettes and CD-ROM</b>. 



<br>

<br>Click <a href="order.html">HERE</a> to go to a page where 

you can order software and <b>forms</b> which you can <b>download</b>, 

including a truncated version of <a href="abc_soft.html">ABC Software</a>

for Windows ("Personal Edition").

<br>

<br>Order on-line using this form 

or email your responses to this form to XYZ Company at 

<a href="mailto:xyz@rksoftware.com">xyz@rksoftware.com</a> or 

call (800)555-5555 or +1(123)876-9876 or fax to (123)876-9876.<r> 



<br><b>*** A 10% restocking charge will be applied to all returns 

***</b>

<br>

<br>Please add shipping charges where indicated. We look forward to serving you.

<hr>

You can also order by mail with a check or money order. Make sure to include shipping/

handling charges, as shown below, in US dollars to:<br><br>RK Software, Inc. 



<br>555 Anywhere St.

<br>Beautyville FL 32256 USA

<hr>



<FORM method=POST  ACTION="mailto:74172.1154@compuserve.com">



<INPUT TYPE="hidden" NAME="recipient" VALUE="xyz@rksoftware.com">



<INPUT TYPE="hidden" NAME="Subject" VALUE="Software Order">





<pre><b>Select one</b> (required): <INPUT TYPE="radio" NAME="card_type" 

VALUE="VISA" CHECKED>VISA <INPUT TYPE="radio" NAME="card_type" 

VALUE="MC" >MasterCard <INPUT TYPE="radio" NAME="card_type" 

VALUE="AMEX" >American Express</pre>

    

</menu>

 

<PRE><b>Credit Card Number</b> (required):         

<INPUT TYPE="text" NAME="Credit_Card_Number" SIZE=25>

<b>Expiration date</b> (required):            

<INPUT TYPE="text" NAME="Expiration" SIZE=5>



<b>Shipping address</b>:

    

    <b>Ship To Name</b> 

(required):          <INPUT TYPE="text" NAME="Ship_To_Name" SIZE=40>

    

<b>Company Name</b>: <INPUT TYPE="text" NAME="Company_Name" SIZE=40>

    <b>Street Address </b> (required):

<INPUT TYPE="text" NAME="Ship_To_Addr_(line_1)" SIZE=40>

    

FedEx will not deliver to U.S. Post Office Box

    <b>Ship To Address (line 2)</b>:                <INPUT TYPE="text

	" NAME="Ship_To_Addr_(line_2)" SIZE=40>

    <b>Ship To City</b> (required):                 <INPUT TYPE="text

	" NAME="Ship_To_City" SIZE=40>

    <b>Ship To State/Province</b> (required):       <INPUT TYPE="text

	" NAME="Ship_To_State/Province" SIZE=12>

    <b>Ship To Zip/Postal Code</b> (required):      <INPUT TYPE="text

	" NAME="Ship_To_Zip/Postal_Code" SIZE=10>

    <b>Ship To Country</b> (required):              <INPUT TYPE="text

	" NAME="Ship_To_Country" SIZE=15>

    <b>Telephone number</b> (required):             <INPUT TYPE="text

	" NAME="Telephone" SIZE=13>

    <b>Fax number</b>:                              <INPUT TYPE="text

	" NAME="fax" SIZE=13>

    <b>E-mail address</b>:                          <INPUT TYPE="text

	" NAME=                                                "e-mail" SIZE=25>

<br><b>Please enter the billing address of your credit card, if different from the

shipping address.</b>

<b>(Please enter your name AS IT APPEARs ON YOUR CREDIT CARD)</b>

    <b>Name:</b>                          

<INPUT TYPE="text" NAME="Name" SIZE=40>

    <b>Address (line 1):</b>              

<INPUT TYPE="text" NAME="Address_(line_1)" SIZE=40>

    <b>Address (line 2):    

</b>          <INPUT TYPE="text" NAME="Address_(line_2)" SIZE=40>

    

<b>City:</b>                          

<INPUT TYPE="text" NAME="City_or_town" SIZE=40>

    <b>State or Province:</b>             

<INPUT TYPE="text" NAME="State_or_Province" SIZE=12>

    <b>Zip/Postal Code:</b>               

<INPUT TYPE="text" NAME="Zip/Postal_Code:" SIZE=10>

    <b>Country:</b>                       

<INPUT TYPE="text" NAME="Country" SIZE=15>

</PRE>

    <p>

    </menu>

    

<p>Please indicate the program(s) you wish to order by checking them off:<br>

    <p>

  

<b> <INPUT TYPE="checkbox" NAME="programs_ordered" VALUE="My Software Lite 

CD-ROM- $99"><a href="my_soft.html">My Software Lite</a> v.2.0 for Windows CD-ROM - 

- $99 <br>

</b>--> For additional licences at the same location or on a network please call, 

write or fax our office.

<br>    --><i> My Software Lite </i> comes with a 60-day return guarantee. A 10%

restocking fee applies <br>    

--> to all returns. 

Shipping & handling charges are not refundable.

<br><br>

<b>    

<INPUT TYPE="checkbox" NAME="programs_ordered" VALUE="My Software Pro - 

- $149"><a href="my_softpro.html"> My Software Pro </a> 

v. 2.0 for Windows -diskettes - - - - - $149</b> 



<br>    --><i> 

My Software Pro </i> comes with a 30-day return guarantee. 

A 10% restocking fee applies 

<br>    --> to all returns. 

Shipping & handling charges are not refundable.

<br>    --> 

You can also order a <b> downloadable</b>, truncated version of 

My Software Pro, called <br>    --> <i> My Software Pro 

<b>Personal Edition</b></i> for <b> only $69 (non-refundable) 

<a href="order.html"> |HERE|</a></b>

<br><br>

    

<br><br>

<hr>

<b><i><u>Shipping and Handling Charges: 

</u></i></b> 

<br><i>My Software Lite</i> and <i>My Software Pro</i> are shipped by

<b>Federal Express courier</b>. Other products "best way".<br><br>



Add <b>$12</b> for delivery of <i>My Software Lite</i> or <i>My Software

Pro</i> within the U.S. or <b>$25</b> to Mexico and Canada, <b>$45 - $75</b>

outside N. America, depending on location, except Demo and where otherwise indicated. 



<br><br>

Overseas demo shipment costs $5 (total $10). <br>

 

<p><hr>How did you come upon our home page, or who referred you here?

Any comments or questions?<br> 

   

<TEXTAREA name="Referred_by" rows=3 cols=60></TEXTAREA>



<p>

<hr>Thank you for your order!

    <p><INPUT 

TYPE="hidden" NAME="WebFormID" VALUE="2">

    <p>Click 

here to <INPUT TYPE="submit" VALUE="Send Your Order Now">

.................... or <INPUT TYPE="reset" VALUE="Clear">

the form and start over.</FORM>

<p>



<hr>



Return to <a href="index.html"><img src="central3.gif"alt="RK 

Software logo">RK Software Home Page</a>



<hr><FONT SIZE=-2>(C)1996 

RK Software.</FONT>

</body>

You are visitor <img src="/cgi-bin/Count.cgi?ft=3&dd=C&frgb=0;0;0|df=rksoft-index.dat"

align=absmiddl> since 1-Dec-1995

</html>


Listing 20.2 shows the results obtained by using the mailto: command.


Listing 20.2 Results obtained by using the mailto: command.

Subject: Form posted from AIR Mosaic

Content-type: application/x-www-form-urlencoded

Content-length: 567

X-Mailer: AIR Mosaic (16-bit) version 1.00.198.07

WebFormID=2&Referred_by=&programs_ordered=My%20Software%20Lite%20%0D%0ACD-ROM-

 %20%2499&Country=&Zip/Postal_Code:=&State_or_Province=&City_or_town=&Address_

 (line_2)=&Address_(line_1)=&Name=&email=&fax=&Telephone=&Ship_To_Country=USA&Ship_To_Zip/

 Postal_Code=45632&Ship_To_State/Province=FL&Ship_To_City=Bonnesville&Ship_To_

 Addr_(line_2)=&Ship_To_Addr_(line_1)=456%20Whatever%20Street&Company_

 Name=XYZ%20Corporation&Ship_To_Name=XYZ%20Corporation&Expiration=9%2f99&Credit_

 Card_Number=1234567890123456&card_type=VISA&Subject=Software%20Order&recipient=

 xyz@rksoftware.com


As you can see, the e-mail received using the mailto: command is not easily readable. It needs to be parsed before you can decipher what it contains. A CGI script or program comes in handy here because a CGI script would parse the message into a readable format before it is sent.

Listing 20.3 shows the HTML code that uses a CGI script to send the same order information from the browser to the Web server. Notice the following line in Listing 20.3:


<FORM method=POST  ACTION="http://www.rksoft.net/cgi-bin/formmail.pl">

The preceding line invokes the CGI script, formmail.pl, written in Perl and residing on the Web server in the cgi-bin directory.


Listing 20.3. HTML sample using CGI for ordering software.

<html>

<head>

<title>Order Desk 



</title>

</head>

<BODY background="wrbgrnd6.gif" 

bgproperties="fixed">

<center>

<h1>   Order Desk <a href="ita.html">

<img border=0 align="middle" src="itlogo2f.gif" alt="RK Software logo"></a> 

<img src="amex.gif"> <img src="mastercd.gif">  <img src="visacard.gif">

</h1>

<br><a href="order.html"><img src="ordpgbu7.gif" align="middle" 

alt="Go to DOWNLOADABLES Order Form" border=0></a> . 

<a href="customer_service.html"><img src="custsbut.gif" 

border=0 align="middle" alt="Customer Service / FAQ">

</a>

</center>

<hr>

<br><b>USE OF THIS FORM</B>

<br>

<br>

This page is for ordering software on <b>diskettes and CD-ROM</b>. 



<br>

<br>Click <a href="order.html">HERE</a> to go to a page where 

you can order software and <b>forms</b> which you can <b>download</b>, 

including a truncated version of <a href="abc_soft.html">ABC Software</a> for Windows

("Personal Edition").

<br>

<br>Order on-line using this form or email your responses to this form to XYZ Company at

<a href="mailto:xyz@rksoftware.com">xyz@rksoftware.com</a> or 

call (800)555-5555 or +1(123)876-9876 or fax to (123)876-9876.<r> 



<br><b>*** A 10% restocking charge will be applied to all returns 

***</b>

<br>

<br>Please add shipping charges where indicated. We look forward to serving you.

<hr>

You can also order by mail with a check or money order. Make sure to include shipping/

handling charges,

as shown below, in US dollars to:<br><br>RK Software, Inc. 



<br>555 Anywhere St.

<br>Beautyville FL 32256 USA

<hr>



<FORM method=POST  ACTION="http://www.rksoft.net/cgi-bin/formmail.pl">



<INPUT TYPE="hidden" NAME="recipient" VALUE="xyz@rksoftware.com">



<INPUT TYPE="hidden" NAME="Subject" VALUE="Software Order">



<pre><b>Select one</b> (required): <INPUT TYPE="radio" NAME="card_type" 

VALUE="VISA" CHECKED>VISA <INPUT TYPE="radio" NAME="card_type" 

VALUE="MC" >MasterCard <INPUT TYPE="radio" NAME="card_type" 

VALUE="AMEX" >American Express</pre>

    

</menu>

 

<PRE><b>Credit Card Number</b> (required):         

<INPUT TYPE="text" NAME="Credit_Card_Number" SIZE=25>

<b>Expiration date</b> (required):            

<INPUT TYPE="text" NAME="Expiration" SIZE=5>

   

<b>Shipping address</b>:

    

    <b>Ship To Name</b> 

(required):                 <INPUT TYPE="text" NAME="Ship_To_Name" SIZE=40>

    

<b>Company Name</b>:                            <INPUT TYPE="text" 

NAME="Company_Name" SIZE=40>

    <b>Street Address </b> (required):

<INPUT TYPE="text" NAME="Ship_To_Addr_(line_1)" SIZE=40>

    

FedEx will not deliver to U.S. Post Office Box

    <b>Ship To Address (line 2)</b>:                <INPUT TYPE="text"

	NAME="Ship_To_Addr_(line_2)" SIZE=40>

    <b>Ship To City</b> (required):                 <INPUT TYPE="text"

	NAME="Ship_To_City" SIZE=40>

    <b>Ship To State/Province</b> (required):       <INPUT TYPE="text"

	NAME="Ship_To_State/Province" SIZE=12>

    <b>Ship To Zip/Postal Code</b> (required):      <INPUT TYPE="text"

	NAME="Ship_To_Zip/Postal_Code" SIZE=10>

    <b>Ship To Country</b> (required):              <INPUT TYPE="text"

	NAME="Ship_To_Country" SIZE=15>

    <b>Telephone number</b> (required):             <INPUT TYPE="text"

	NAME="Telephone" SIZE=13>

    <b>Fax number</b>:                              <INPUT TYPE="text"

	NAME="fax" SIZE=13>

    <b>E-mail address</b>:                          <INPUT TYPE="text"

	NAME=

                                                                                                                 

    "e-mail" SIZE=25>

<br><b>Please enter the billing address of your credit card, if different from the

shipping address.</b>

<b>(Please enter your name AS IT APPEARs ON YOUR CREDIT CARD)</b>

    <b>Name:</b>                          

<INPUT TYPE="text" NAME="Name" SIZE=40>

    <b>Address (line 1):</b>              

<INPUT TYPE="text" NAME="Address_(line_1)" SIZE=40>

    <b>Address (line 2):    

</b>          <INPUT TYPE="text" NAME="Address_(line_2)" SIZE=40>

    

<b>City:</b>                          

<INPUT TYPE="text" NAME="City_or_town" SIZE=40>

    <b>State or Province:</b>             

<INPUT TYPE="text" NAME="State_or_Province" SIZE=12>

    <b>Zip/Postal Code:</b>               

<INPUT TYPE="text" NAME="Zip/Postal_Code:" SIZE=10>

    <b>Country:</b>                       

<INPUT TYPE="text" NAME="Country" SIZE=15>

</PRE>

    <p>

    </menu>

    

<p>Please indicate the program(s) you wish to order by checking them off:<br>

    <p>

  

<b> <INPUT TYPE="checkbox" NAME="programs_ordered" VALUE="My Software Lite 

CD-ROM- $99"><a href="my_soft.html">My Software Lite</a> v.2.0 for Windows CD-ROM - 

- $99 <br>

</b>--> For additional licences at the same location or on a network please call, 

write or fax our office. <br>    --><i> My Software Lite </i> comes with a 60-day 

return guarantee. A 10% restocking fee applies <br>    --> to all returns. 

Shipping & handling charges are not refundable. <br><br>

<b>    

<INPUT TYPE="checkbox" NAME="programs_ordered" VALUE="My Software Pro - 

- $149"><a href="my_softpro.html"> My Software Pro </a> 

v. 2.0 for Windows -diskettes - - - - - $149</b> 



<br>    --><i> 

My Software Pro </i> comes with a 30-day return guarantee. A 10%restocking fee applies

<br>

--> to all returns. Shipping & handling charges are not refundable.

<br>    --> 

You can also order a <b> downloadable</b>, truncated version of My Software Pro, called

<br>

--> <i> My Software Pro <b>Personal Edition</b></i> for <b> only $69

(non-refundable) <a href="order.html"> 

|HERE|</a></b><br><br>

    

<br><br>

<hr>

<b><i><u>Shipping and Handling Charges: 

</u></i></b> 

<br><i>My Software Lite</i> and <i>My Software Pro</i> are shipped by <b>Federal 

Express courier</b>. Other products "best way".<br><br>



Add <b>$12</b> for delivery of <i>My Software Lite</i> or <i>My Software Pro</i>

within the U.S. or <b>$25</b> to Mexico and Canada, <b>$45 - $75</b> outside N. America,

depending on location, except Demo and where otherwise indicated. 



<br><br>

Overseas demo shipment costs $5 (total $10). <br>

 

<p><hr>How did you come upon our home page, or who referred you here?

Any comments or questions?<br> 

   

<TEXTAREA name="Referred_by" rows=3 cols=60></TEXTAREA>



<p>

<hr>Thank you for your order!

    <p><INPUT 

TYPE="hidden" NAME="WebFormID" VALUE="2">

    <p>Click here to <INPUT TYPE="submit" VALUE="Send Your Order Now">

	.................... or <INPUT TYPE="reset" VALUE="Clear"> the form and start over.

</FORM>

<p>



<hr>



Return to <a href="index.html"><img src="central3.gif" alt="RK Software

logo">RK Software Home Page</a>



<hr><FONT SIZE=-2>(C)1996 

RK Software.</FONT>

</body>

You are visitor <img src="/cgi-bin/Count.cgi?ft=3&dd=C&frgb=0;0;0|df=rksoft-index.dat"

align=absmiddl> since 1-Dec-1995

</html>


Listing 20.4 shows the results obtained by using a CGI script.


Listing 20.4. Results obtained by using a CGI script.

Subject: Form posted from AIR Mosaic

Content-type: application/x-www-form-urlencoded

Content-length: 567

X-Mailer: AIR Mosaic (16-bit) version 1.00.198.07

WebFormID=2

Referred_by=

programs_ordered=My Software Lite CD-ROM

Country=

Zip/Postal_Code:=

State_or_Province=

City_or_town=

Address_(line_2)=

Address_(line_1)=

Name=

email=

fax=

Telephone=

Ship_To_Country=USA

Ship_To_Zip/Postal_Code=45632

Ship_To_State/Province=FL

Ship_To_City=Bonnesville

Ship_To_Addr_(line_2)=

Ship_To_Addr_(line_1)=456 Whatever Street

Company_Name=XYZ Corporation

Ship_To_Name=XYZ Corporation

Expiration=9/99

Credit_Card_Number=1234567890123456

card_type=VISA

Subject=Software Order

recipient=xyz@rksoftware.com


This result appears much more readable! The CGI script included in Listing 20.4 processes the data received from the Web form and e-mails it to you in a meaningful form. You receive the customer order as simple ASCII text that is easily readable.

CGI scripting performs this kind of task and much more. CGI scripts help connect your Web site to a relational database, which enables visitors and customers to easily browse and search your product catalog. Airlines can set up sites that let their customers inquire about flight schedules and make reservations online. Banks can set up Web sites that enable their customers to check balances and make transfers. Libraries can set up sites that enable readers to search for books and magazines. A CGI program can send data back to the browser, making the communication a two-way traffic.

CGI is not a programming language. It represents a simple communication protocol that establishes the communication layer between the server and the server-side applications. Figure 20.2 shows the architecture of a CGI-based Web application.

Figure 20.2 : Architecture of a CGI application.

A CGI program is nothing but a simple application that accepts input, processes it, and sends the resulting output to its appropriate destination. Therefore, you can use any standard programming or scripting language that supports input/output processing to write your CGI programs. Potential candidates include C/C++, Visual Basic, Perl, or FORTRAN. If you use C/C++ or Visual Basic, you create a CGI program. A CGI program is an executable, similar to the executables you create for your desktop client/server applications. If you use a scripting language such as Perl or AppleScript, you create a CGI script. You will find it easier to create and maintain a script. Any changes made to a program must undergo the compile, link, and build process before the program can be executed. Whether you choose to create a program or script depends on the tool you plan to use. The choice of tool depends on your familiarity with the tool and its programming syntax and structure. If you programmed with C/C++ all your life, you may feel better using C/C++ to write your CGI programs. In fact, you may be able to reuse your library of C/C++ routines for some of your CGI programs. On the other hand, if you are an avid Visual Basic developer, you probably want to continue using it to write your CGI programs.

CGI programs reside on the server. They benefit from faster and better processing power of the server. The more powerful the server, the better execution and response time you get from your CGI programs. At the same time, you should pay special attention when writing your CGI program code. The code should be efficient and fast. In the preceding example, if the CGI program takes a long time to convert the order form data into simple ASCII, you would get all your e-mail notifications late. Your ability to process the orders on a timely basis would suffer. The standard programming rules to write clean, modular, and efficient code also apply to CGI programming.

CGI Specification

The CGI specification came from Rob McCool of Netscape Communications. At the moment, the specification is under the supervision of the World Wide Web Consortium (W3C-http://www.w3.org).

The CGI specification enables you to expand the capabilities of your server. It serves as a gateway between the Web server and other server processes including databases.

NOTE
Other server APIs exist in the marketplace in addition to the CGI API. These include Netscape's NSAPI (Netscape Server Application Programming Interface) and Microsoft's ISAPI (Internet Server Application Programming Interface).

The Web server captures the HTML form data into environment variables. A CGI script reads the environment variables, processes the data, and sends the response back to the browser. The form data is received as a set of name-value pairs. These pairs are separated by the & sign. The name and value tags are separated by the = sign. Because each name=value pair is URL encoded, the following conversion must occur:

  1. Convert all + characters to spaces.
  2. Convert all %xx sequences to the single character whose ASCII value is xx in hexadecimal form.

The form data gets stored in the environment variable QUERY_STRING if the GET method is used in the FORM tag for submission. If the POST method is used in the FORM tag for submission, the form data is not stored in any environment variables. You get it from STDIN. Because the server does not send an EOF at the end of the data, use the environment variable CONTENT_LENGTH to determine the number of bytes to be read. The next section, "CGI Environment Variables," outlines the different variables available for storing and processing data.

A number of scripts exist on the World Wide Web that do the preceding conversion. These scripts come in a number of different languages, including the Bourne Shell, C, Perl, Perl5, TCL, and many more.

You can send different types of data back to the browser including HTML, GIF, and other MIME Content-Types. For example, to send HTML data, use the Content-Type of text/html. To send a GIF image, use the Content-Type of image/gif.

The Win-CGI standard is a CGI standard supported by some Windows-based Web servers.

NOTE
In the Win-CGI standard, the data gets stored in INI files instead of environment variables. The use of INI files is widespread and very common on the Windows platform.

If you write CGI programs (executables, for example), the executables usually appear in the \cgi-bin\ directory on the server and the source code is stored in the \cgi-src\ directory. Security measures must exist to control access to both these directories.

If you write CGI scripts, they usually get stored in the \cgi-bin\ directory. Because the script is its own source, you don't need to store anything in the \cgi-src\ directory. Again, security measures must exist to control access to the \cgi-bin\ directory-especially in this case, because the script is the source code itself.

CGI Environment Variables

The following CGI environment variables are set for all requests:

The following environment variables are specific to the request being fulfilled by the gateway program:

Architecture of a CGI Application

In order to pass data about the information request from the server to the script, the server uses command-line arguments, as well as environment variables. These environment variables get set when the server executes the gateway program.

Figure 20.2 describes the World Wide Web architecture of which CGI is one part. The Web browser is the client and it can interact with other applications such as Microsoft Word, Microsoft Excel, and Microsoft PowerPoint, depending on the nature of the application. The client connects to the Web server via the network. Several applications can reside on the server. The CGI interface acts as the gateway between the Web server and the server-side processes. One of the server-side processes could be a relational database. Although CGI acts as a gateway between any type of Web server and server-side applications, it has been more commonly implemented with the HTTPd server.

The client browser invokes the CGI script and waits until the CGI script completes its process. Thus, the CGI script must execute fast enough to have no perceived delay in the response time.

The drawback of using CGI is that every time a CGI script is invoked, the Web server spawns a new process. This setup becomes a problem when a given Web site gets frequently accessed by several users. It results in the Web server spawning a plethora of processes.

In the previous example, the CGI script processes the form order and notifies the company about receiving a customer order. You can extend the script further to dial into a credit card bureau and check the validity of the credit card number provided by the customer. The script can notify the customer about the acceptance or denial of the order. If the order gets accepted, the customer receives an order reference number. If the order is not accepted, the denial reasons are indicated.

CGI Versus VBScript

Certain tasks exist that could be easily performed on the client side with VBScript, thus avoiding the use of CGI programs. For example, processing mouse clicks and validating user input, come to mind. Consider the example of validating user input on the client side itself before the data goes to the server. Validating user input before it goes to the server represents good programming practice because the server's processing power can be better utilized for other important tasks.

Not everything can be implemented using VBScript. In some cases, you still need to consider CGI as a possible option for your application. For example, if your application needs to communicate with a back-end database, CGI provides one way to implement it, whereas VBScript doesn't work for such tasks. Whether you use VBScript or CGI, or both, depends on the nature of your application, as well as your familiarity with VBScript and CGI.

NOTE
VBScript programming is much simpler than CGI programming. If this represents your first foray into Web programming using CGI, expect a significant learning curve using and experimenting with CGI. On the other hand, VBScript coding is simpler because of the BASIC language syntax it follows.

Examples

This section reviews and analyzes a VBScript example downloaded from the Web site http://www.microsoft.com/vbscript. Figure 20.3 shows a simple Web page created by the HTML code included in the file msftd.html on the companion CD-ROM. This HTML displays an order form that enables you to place orders for flowers. You specify the occasion and enter the name and address where the flowers should be sent.

Figure 20.3 : Ordering flowers Web page created using HTML and VBScript.

Look at the code part by part. Listing 20.5 represents all the HTML code used to set up the form. Three radio buttons are displayed so the user can select Birthday (default), Anniversary, or Get well soon. These buttons are displayed using the <Input Type> tag. This part of the code remains the same no matter whether you use CGI or VBScript.

Next, you add the data-entry fields for entering name and address of the destination. The <Input> tag is used to add these fields. Three buttons-Submit, Clear, and Init-are added at the bottom. The Submit button sends the order. The Clear button clears the name and address fields. The Init button initializes the data-entry fields.

If you use CGI scripts to process user input and mouse clicks, you would include reference to those scripts in your HTML code. For example, the Submit button would include a reference to a CGI script residing on the server. This script is invoked when the user clicks the Submit button. The mouse click gets processed on the server and the results are transmitted back to the browser. This process becomes expensive because every such event would be processed on the server. It also increases network traffic and loads the server with trivial tasks that could easily be processed on the client side. Consequently, you have a very inefficient use of the server and its processing power.


Listing 20.5. HTML code for setting up the form for ordering flowers.

<HEAD><TITLE>VBScript sample:  Ordering Flowers</TITLE></HEAD>

<BODY>



<TABLE  WIDTH="80%">

<TR VALIGN=bottom>

<TD WIDTH="40%"><IMG SRC="/vbscript/us/vbssamp/msftd/

msftd.gif" ALIGN=center></TD>

<TD WIDTH="60%"><FONT SIZE=12><I>Order Flowers

</I></FONT></TD>

</TR>

</TABLE>



<FONT FACE="Times New Roman" SIZE=4>What is the occasion?

</FONT><BR>

<PRE>

<INPUT TYPE=RADIO NAME=OptOccasion CHECKED> Birthday



<INPUT TYPE=RADIO NAME=OptOccasion> Anniversary



<INPUT TYPE=RADIO NAME=OptOccasion> Get well soon

</PRE>



<FONT FACE="Times New Roman" SIZE=4>When and where should the flowers be sent?

</FONT><BR>

<PRE>

Date     <INPUT NAME=TxtDate  SIZE=60>



Name     <INPUT NAME=TxtName  SIZE=60>



Address  <INPUT NAME=TxtAddress SIZE=60>



City     <INPUT NAME=TxtCity SIZE=60>



State    <INPUT NAME=TxtState SIZE=60>



Zip code <INPUT NAME=TxtZip SIZE=60>



<INPUT TYPE=BUTTON VALUE="Submit" NAME="BtnSubmit">

<INPUT TYPE=BUTTON VALUE="Clear" NAME="BtnClear">

<INPUT TYPE=BUTTON VALUE="Init" NAME="BtnInit"><BR>

</PRE>


Listing 20.6 shows the VBScript code used to process the data entered by the user. This code also processes the mouse click events when the user clicks the Submit, Clear, or Init buttons. Prior to JavaScript and VBScript, such processing would occur on the server using CGI programs and scripts. VBScript extends the HTML code and validates user input before it is sent to the server. This setup reduces network traffic, decreases server load, and improves the overall performance of your Web page.

Two variants and six procedures get defined: strMsgBoxTitle and bValidOrder and Window_OnLoad, BtnInit_OnClick, BtnSubmit_OnClick, ValidateDeliveryDate, CheckSpecified, and BtnClear_OnClick.

The subroutine Window_OnLoad gets executed when the Web page window is first loaded by the browser. It assigns the value MSFID to the variant strMsgBoxTitle. The variant StrMsgBoxTitle is assigned a string value; therefore, it is now a string variable. The strMsgBoxTitle is used to display the title for the message box. Next the subroutine Window_OnLoad calls the BtnInit_OnClick procedure. This procedure initializes the data-entry fields.

The procedure BtnInit_OnClick initializes the data-entry fields. It is executed when the Web page window is first loaded. It also gets executed when the user clicks the Init button.

The procedure BtnSubmit_OnClick gets executed when the user clicks the Submit button. It checks to make sure if the data entered is valid. If it is valid, the variable bValidOrder is initialized to true at the beginning of this procedure and retains its initialized value. If bValidOrder is true, the order gets sent. If the data entered is invalid, bValidOrder is set to false and the control is returned to the user on the Web page.

The procedure ValidDeliveryDate determines whether the value specified in the date field is valid.

The procedure CheckSpecified is actually called by the BtnSubmit_OnClick procedure. It determines whether the data entered in name and address fields is valid.

The procedure BtnClear_OnClick is executed when the user clicks the Clear button. It clears the data-entry fields.


Listing 20.6. VBScript code for processing mouse clicks and user input.

<SCRIPT LANGUAGE="VBScript">

<!--

Option Explicit



Dim strMsgBoxTitle

Dim bValidOrder



Sub Window_OnLoad

    strMsgBoxTitle = "MSFTD"

    Call BtnInit_OnClick

End Sub



Sub BtnInit_OnClick

    TxtName.Value = "Joe Smith"

    TxtAddress.Value = "1 Main Street"

    TxtCity.Value = "Springfield"

    TxtState.Value = "Washington"

    TxtZip.Value = "12345"

    TxtDate.Value = Date + 3

End Sub



Sub BtnSubmit_OnClick

    bValidOrder = True

    Call CheckSpecified(txtName.Value, "Please specify a name.")

    Call CheckSpecified(txtAddress.Value, "Please specify an address.")

    Call CheckSpecified(txtCity.Value, "Please specify a city.")

    Call CheckSpecified(txtState.Value, "Please specify a state.")

    Call CheckSpecified(txtZip.Value, "Please specify a zip code.")

    Call CheckSpecified(txtDate.Value, "Please specify a date.")

    Call ValidateDeliveryDate

    If bValidOrder Then

        MsgBox "Thank you for your order!", 0, strMsgBoxTitle



        ' TODO:  Actually send the order.

    End If

End Sub



Sub ValidateDeliveryDate

    Dim SoonestWeCanDeliver

    Dim RequestedDate



    If Not bValidOrder Then Exit Sub



    SoonestWeCanDeliver = Date + 2

    RequestedDate = CDate(TxtDate.Value)

    If RequestedDate < SoonestWeCanDeliver Then

       bValidOrder = False

       MsgBox "Not even we can deliver that fast!", 0, strMsgBoxTitle

    End If

End Sub



Sub CheckSpecified(ByVal strFieldValue, ByVal strMsg)

    If strFieldValue = "" And bValidOrder Then

       MsgBox strMsg, 0, strMsgBoxTitle

       bValidOrder = False

    End If

End Sub



Sub BtnClear_OnClick

    TxtName.Value = ""

    TxtAddress.Value = ""

    TxtCity.Value = ""

    TxtState.Value = ""

    TxtZip.Value = ""

    TxtDate.Value = ""

End Sub



-->

</SCRIPT>


The remaining part of the code is again all HTML. It remains the same no matter whether you use CGI or VBScript. In this example, all the VBScript code is encapsulated between the <SCRIPT> and </SCRIPT> tags. The entire code resides in a single location within the body of the HTML code, making the code modular and easy to locate. The VBScript code is listed in the <BODY> section of the HTML code.

Relevant Web Sites

Table 20.1 lists few Web sites for more information on CGI and VBScript. Plenty of resources and examples exist on the Internet.

Table 20.1. Relevant Web sites.

Site NameSite URL
World Wide Web Consortiumhttp://www.w3.org
Perl CGI scripts for Internet Retailers http://phoenixrise.com/CCC/cindex.html
VBScripthttp://www.microsoft.com/vbscript
VBScript linkshttp://www.microsoft.com/vbscript/us/
vbsmain/vbslinks.htm

Review

CGI represents a simple protocol of communication between the Web forms and your programs that reside on the Web server. A CGI script or program gets its input from the Web forms, processes it, and sends the results back to your browser. CGI is not a programming language; it is a script or a program that resides on the server. You can create a CGI script or program using almost any programming language that supports standard input and output processing. For example, you can use C/C++, Visual Basic, Perl, or FORTRAN to write your CGI programs. The best language to use is the one that you feel familiar with and comfortable using. Whatever you choose, make sure your CGI programs process data efficiently and respond quickly. Remember, CGI programs get their input from the Web forms, and the user waits for the response while the data is being processed. Therefore, the CGI programs need to respond quickly.

You have two important decisions to make about CGI early on for your project. First, decide whether your project demands the use of CGI. Then, you have to decide how to protect the CGI programs. Because a CGI program is invoked as a result of user action through the browser, you need to undertake necessary security precautions. The CGI programs should be under direct control of the Webmaster only and all others should have only execute rights.

VBScript programming is simpler than CGI programming. This chapter introduced CGI and explained the different CGI environment variables. It compared CGI with VBScript and identified how VBScript can be used to handle some of the processing on the client side, thus eliminating or reducing the need for CGI scripts and reducing the load on the network and server. Data communication in a CGI-based web architecture was also discussed. This chapter also included examples of VBScript code for processing mouse clicks and user input. There is plenty of resources and examples available on the Net. A list of few relevant and useful web sites is included in this chapter. Be sure to visit the Microsoft VBScript site regularly to keep abreast of the latest on Microsoft Internet Explorer and VBScript. VBScript is the new kid on the block and it is expected to grow and evolve over time.

If you use CGI scripts to process user input and mouse clicks, you load the server with many trivial tasks that could very easily be handled on the client side. You also increase network traffic. This setup creates an inefficient use of the server and its processing power. Using VBScript to handle such tasks reduces network traffic and server load.