Lab 4

Lab 4

Forms & PHP Intro


Goals

Learn about...

  1. HTML From Elements
  2. Form Submission Concept
  3. Connecting Forms to PHP scripts
  4. GET and POST methods

Setup

Connecting to web server via FTP

Connection details have been emailed to you.

In lab, I will demonstrate how to use WinSCP to connect to our remote server.

Here are the server details:


I. Login form (HTML)

  1. Open Notepad++ or your editor of choice
  2. Create a new document and save it as login.html in your lab4 folder
  3. Cut and paste this starter code into your login.html file
  4. Add the attributes action = "login.php" and method = "post" to the form tag
  5. Inside the form tag, add a label tag with the content "Username:"
  6. Below "Username:" and inside the label tag, add an input tag with the attributes type = "text" and name = "user"
  7. Below the label tag and inside the form tag, add another label tag with the content "Password:"
  8. Below "Password:" and inside the label tag, add an input tag with the attributes type = "password" and name = "pswd"
  9. Below the second label tag and inside the form tag, add an input with the attributes type = "submit" and value = "Login"
  10. Make sure login.html is saved to your lab4 folder.

II. Login script (PHP)

  1. In Notepad++ or your editor of choice, create a new document and save it as login.php in your lab4 folder
  2. Be sure the file is named with the .php file extension.
  3. Add the following code:
    <?		
      $u = $_POST['user'];
      if ($u == '') {
        echo '<p>The submitted username was blank</p>';
      }
    ?>
    
  4. Notice that PHP code must be inside of the special brackets <? php code ?>
  5. Below the variable $u, set the variables $p to the password that was sent from the posted form. Hint: The $_POST array index is the name of the form element you wish to get
  6. Below the if statement, add another if statement to echo a paragraph indicating that the password was blank. Use the existing if statement has a model
  7. Notice that we can compare a PHP string variable to the empty string, i.e., '' by using the == operator
  8. Below the second if statement, add an if else statement to do the following:
    • if $p and $u are not blank, echo a paragraph that say "User $u is logged in"
    • else, echo a hyperlink back to the login.html page
  9. Hints:
    • If your printed HTML does not have double quotes, you can use double quotes in PHP to print a variable's value directly in a string, i.e., "User $u is logged in"
    • If your printed HTML does have double quotes, you can slice a variable's value into the string using the concatenation operator, i.e., '<a href="login.html">'.$variable.'</a>'
  10. Using WinSCP, upload your lab4 folder to your remote server
  11. Open Chrome and go to your URL, i.e., username.siencs.com/lab4 or username.breimer.net/lab4 to test your login script.

Key Concept: please read as you will be quizzed on this later

When an HTML form has an action attribute, clicking the submit button triggers an HTTP request and uses the value of the action as the URL. Typically, the value will be a relative URL, which implies that the form (HTML file) and script (PHP file) are in the same folder on the server.

Task Check

Show your instructor login.html working on the web server.


III. A better approach (no HTML file)

Key Concept: please read as you will be quizzed on this later

The login form (HTML file) and the login script (PHP file) can be combined into on PHP script. This allows error messages to be placed directly in the form and the user does not have to ever click a link to go back to the form.

  1. In Notepad++ or your editor of choice, create a new document and save it as betterlogin.php in your lab4 folder
  2. Be sure the file is named with the .php file extension.
  3. Add the following code:
    <? 
    function make_login_form($u = '', $u_error = '') {
      echo '		
      <form action="betterlogin.php" method="post">	
        <label>
          <b>Username: '.$u_error.'</b>
          <input type="text" name="user" value="'.$u.'">
        </label>
    
        <input type="submit" value="Login">
      </form>';
    }
    ?>
    <!DOCTYPE html>
    <html>
      <meta charset="UTF-8">
      <title>Login</title>
      <style>
        label { padding: 10px; display: block;}
        form { padding: 10px; border: 1px solid #888; width: 300px; overflow: auto;}
        input[type='submit'] { float: right; }
      </style>
      <body>
    <?	
      if ($_POST) {
        $u = $_POST['user'];
        if ($u != '') {
          echo '<p>User '.$u.' is logged in.</p>';
        }
        else {
          $u_error = '';
          if ($u == '') {
            $u_error = 'Must enter username';
          }
          make_login_form($u, $u_error);
        }
      }
      else {
        make_login_form();
      }
    ?>
      </body>
    </html>
    
  4. Note how we have two blocks of PHP code and two blocks of HTML code:
    • The first block of PHP code defines a function for generating the form
    • The second block of PHP code processes the form
    • The two blocks of HTML code help define a valid HTML document for displaying the form and the error messages
  5. Modify the make_login_form so that it also generates a label and input for the password
  6. Note you have to add function parameters for the submitted password value ($p) and a possible error message if the password is blank ($p_error)
  7. Modify the 2nd block of PHP code to properly process the password and possible error message. You will fetch the posted password, modify/add if statements to handle if the password is blank, and pass the value and error message to the make_login_form function.
  8. Help (please read carefully):
    • We only process the form if the $_POST variable is not null, otherwise we print a form with no values or error message.
    • If form data was posted by the HTTP request, then we fetch the values of the input elements.
    • If the username and password are both not null, we indicate that the user is logged in. In the future, we will call an authentication function that connects to the user database.
    • If the username and/or password is null, we output the login form and pass the posted values and/or any appropriate error messages.
  9. Using WinSCP, upload your lab4 folder to your remote server
  10. Open Chrome and go to your URL, i.e., username.siencs.com/lab4 or username.breimer.net/lab4 to test your login script.

Key Concept: please read as you will be quizzed on this later

The script that you just created implements a type of recursion. The script generates a form. When the form is submitted, we call the same script again. The form has to handle the base case, which is an initial request for the form with no posted values. Once the form is displayed, clicking the submit button makes a 2nd HTTP request that includes posted values. If the posted values are valid, we will eventually authenticate a user. If the posted values are blank or invalid, we regenerate the form with the previously submitted values and any error messages.

Task Check

Show your instructor betterlogin.php working on the web server.


IV. Working with radio buttons and option selects

Key Concept: please read as you will be quizzed on this later

Rather than hardcode radio buttons and drop down menus (option selects), we can write flexible functions that can also display error messages and remember previously submitted selections.

  1. In Notepad++ or your editor of choice, create a new document and save it as bestlogin.php in your lab4 folder
  2. Be sure the file is named with the .php file extension.
  3. Cut and paste this starter code into your bestlogin.php file

Task

  • Using WinSCP, upload your lab4 folder to your remote server
  • Open Chrome and go to your URL, i.e., username.siencs.com/lab4 or username.breimer.net/lab4 to test the bestlogin.php script
  • Understand how it works and how the previous value is "remembered" before continuing.
    1. Notice that the script has a function for creating a group of radio buttons called make_radio_group. This function generates a group of radio buttons from any array of indices/keys and values.

      The following array
      $options = ['1'=>'Author', '2'=>'Editor', '3'=>'Admin'];

      generates this HTML:

      <div>
        <label><input type="radio" name="role" value="1" >Author</label>
        <label><input type="radio" name="role" value="2" > Editor</label>
        <label><input type="radio" name="role" value="3" > Admin</label>
      </div>
      
    2. Using make_radio_group as a model, creating a function called make_option_group that generates an option select menu. Note that it will take the same three parameters as the make_radio_group function, but it will return the proper HTML to generate a drop-down menu instead of a group of radio buttons.
    3. Your function will generate the following output

      <select name="color">
        <option value="" ></option>
        <option value="#f00">red</option>
        <option value="#0f0">green</option>
        <option value="#00f">blue</option>
      </select>
      

      Given the following array
      $colors = [''=>'', '#f00'=>'red', '#0f0'=>'green', '#00f'=>'blue'];

      Note where the name attribute is located for an option select menu and note that you do not need to specify label tags or use the type attribute.
    4. Inside of make_login_form near the $option array, define a new associative array of colors where the key/index is the 3 digit hex color code and the value is the name of the color (see above).
    5. Inside of make_login_form, call your make_option_group function and pass the color array to generate a color dropdown to your login form. Instead of passing the name "role" pass the name "color", otherwise the form will not submit the color value properly.
    6. Modify the form processing to do the following:
      • Read the color value from the $_POST variables just like you read the username, password and role. Remember that the option group menu is called "color"
      • Make sure the color is not blank before printing the login paragraph message
      • If the color is blank create the proper error message
      • Pass the color value and the new error message to the make_login_form function
      • Be sure to add parameters to the make_login_form function for the color value and new error message.
    7. Finally, use inline CSS to change the color of the login paragraph to the chosen color.

    Task Check

    Show your instructor bestlogin.php working on the web server.


    DELIVERABLE

    Create a zip file of your lab4 folder called lab4.zip and submit the file in Blackboard.

    If applicable, in the comment area of Blackboard put your partner's name.

    Not finished?

    The deliverable must be submitted in Blackboard by midnight on the day before your next scheduled lab meeting. If you wish to work alone, you can submit the deliverable yourself. However, you are encouraged to work with your partner and you can submit together. When submitting as a lab pair, be sure to include your partner's name in the comment area when you submit via Blackboard.

    Do not share

    Outside of lab, you are only permitted to work with your lab partner. Do not share your work with any other student.