Perl/CGI Scripting Exercise 2

Getting Input from Forms

 

  1. As you may know, there are two methods for passing data from HTML forms to scripts: Post & Get. The input from both of these is recorded in environment variables - similar to global variables.
  2. Examine to following script to see the environment variables in action. I saved this file in /var/www/cgi-bin/method.cgi  and chmod 755 the file so it's executable.

 

 

  1. Here's the HTML input that calls this script. Save this file in /var/www/html/method.html

 

 

  1. The ?form=health portion of the action tag will put data in the GET environment variable. This is because all data passed in a URL is stored in the GET variable (same as php). This is an example of passing data by a URL. The output to the browser is shown in Figure 7.2

 


Figure 8.2

 

  1. Before we move on, you need to see how a foreach statement works.  The foreach statement will execute a set of statements for every item in an array.  The format of a foreach statement is as follows:  foreach $element(@array) where $element is the name of the variable to which each successive item from the array will be assigned.  @array is the name of the array that you want to step through.  Notice how this type of block statement is used to parse input from a form in the example below.
  2. Now it's time to actually view the data in a POST or GET method and use this data to do something. Create parseform.cgi in the cgi-bin directory and paste the following text in the file:

 

 

  1. Notice that this method will take in as many variables you pass it and put them into an array called $formdata.
  2. We can call this script by creating a simple input form.  I called this file parseform.html

 

 

  1. Download the parseform.html and put it in the /var/www/html directory.  Also download the parseform.cgi and place it in /var/www/cgi-bin/ directory.
  2. You can find text versions of method.html, method.cgi, parseform.html, & parseform.cgi here

 

 

On Your Own Exercise 2

 

  1. Create a HTML form that has 1 text box, 1 password field, two radio buttons, two checkboxes, 1 pulldown menu and 1 text area for users to input data. Then pass this information to a .cgi file which simply displays all the information entered by the user. A sample of both input and output pages is shown below.
  2. You MUST comment your code to receive full credit!
  3. Use 2 IF statements to decide whether the user owns a bike and/or a car.  If they own a car, print out “I own a car.”  If the user owns a bike, print out “I own a bike.”  If the user doesn’t put a check in the car box, display “I don’t own a car” (or a bike if they don’t check the bike box).

 

 

 

Own Your Own Exercise 2 – Sample Answer