HTML Form Lab

Objectives

A PHP Program Using a GUI

In the previous section you successfully had a browser run your PHP code. In this section you will learn how to use HTML to get information from the user through a graphical user interface (GUI) and how to use that information in your PHP code to change the contents of a web page.

  1. Make an html_form.php file with the usual HTML framework.

  2. Start by adding a paragraph to your body element. The paragraph should include a text asking for the user's first name followed by an input element (also called form control since it is widely used in web forms for users to fill out):
    <form action="<?php $_SERVER['PHP_SELF'] ?>" method="get">
      <label for="fName">First Name: </label><input id="fName" type="text" name="fName"/>
      <label for="lName">Last Name: </label><input id="lName" type="text" name="lName" />
      <input type="submit" value="Submit" />
    </form>
    
    

    This input element:

    Document (add comments), save, publish (i.e. copy into your student web site), validate, and view your enhanced document through a browser. Correct any errors.

  3. If you enter some text in the text field and then leave the field (by pressing the Tab key or clicking on the Submit button, nothing happens. This is because the form action has the Web server to reload this page when the submit button is entered. The PHP global variable, $_SERVER['PHP_SELF'] refers to the page itself.
  4. Next we need to add some PHP code that translates the entered text into a Viking Name.

    Start by creating a PHP script at the beginning of the HTML body.

    <?php 
    if (isset($_GET['fName']) && $_GET['fName'] != "") {
      print("If you were a real Viking, your son's last name would be ". 
      $_GET['fName'] . "sson and your daughter's last name would be " .
      $_GET['fName'] . "sdottir!");
    } else {
    ?>
    

    This script calls the built-in PHP isset() function to test if the variable has been declared and initialized properly. Next it gets the fName variable out of the global $_GET array. Finally a translated Viking name is printed to the HTML page.

  5. Don't forget to end your if/else statement after the HTML text!
    <?php
    }
    ?>
    

HTML References

http://www.w3.org/

http://www.webmonkey.com/