Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Handling HTML Forms with PHP Redux

All of the examples in this chapter and the previous one used two separate scripts for handling HTML forms: one that displayed the form and another that received it. While there's certainly nothing wrong with this method, there are advantages to having the entire process in one script. To have one page both display and handle a form, use a conditional.

if (/* form has been submitted */) {
   // Handle it.
} else {
   // Display it.

To determine if the form has been submitted, I normally check if the $submit variable is set (which is the name of the submit input type in the form).

if (isset($_POST['submit'])) {
   // Handle it.
} else {
   // Display it.
   echo '<input type="submit" name="submit" value="Go!">';
}

If you want a page to handle a form and then display it again (e.g., to add a record to a database and then give an option to add another), use

if (isset($_POST['submit'])) {
   // Handle it.
}
// Display form.

This version of a script will handle a form if it has been submitted and display the form every time the page is loaded.

To demonstrate this important technique, I'll begin writing a registration form, which will be built upon throughout the course of the book.

To handle HTML forms:

  1. Create a new PHP document in your text editor (Script 3.11).
    <?php # Script 3.11 - register.php
    $page_title = 'Register!';
    include ('./header.inc');
    
  2. Write the conditional for handling the form.
    if (isset($_POST['submit'])) {
    
    As I mentioned previously, if the $submit (or $_POST['submit']) variable is set, I know that the form has been submitted and I can process it.
  3. Validate the form.
    if (strlen($_POST['name']) > 0) {
       $name = TRUE;
    } else {
       $name = FALSE;
       echo '<p>You forgot to enter your name!</p>';
    }
    if (strlen($_POST['email']) > 0) {
       $email = TRUE;
    } else {
       $email = FALSE;
       echo '<p>You forgot to enter your email address!</p>';
    }
    if (strlen($_POST['username']) > 0) {
       $username = TRUE;
    } else {
       $username = FALSE;
       echo '<p>You forgot to enter your user name!</p>';
    }
    if (strlen($_POST['password1']) > 0)
    {
       if ($_POST['password1'] ==
    $_POST['password2']) {
          $password = TRUE;
         } else {
          $password = FALSE;
          echo '<p>Your password did not match the confirmed password!</p>';
       }
    } else {
       $password = FALSE;
       echo '<p>You forgot to enter your password!</p>';
    }
    if ($name && $email && $username && $password) {
       echo '<p>You are now registered.</p>';
    } else {
       echo '<p>Please go back and try again.</p>';
    }
    
    The process I use for checking the HTML form is like that which I developed in Chapter 2, "Programming with PHP." Since each of the inputs are strings, I confirm that they have a positive length. If so, I set the appropriate variable name to TRUE; if not, I set the variable to FALSE and print an error message. The password input will also be compared against the confirmed password. If the validation passes all of the tests, the user will be registered; otherwise, the user will be asked to try again. The actual registration process itself will be developed in Chapter 6, "Using PHP and MySQL."
  4. Complete the main conditional and display the HTML form.
    } else {
    ?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <fieldset><legend>Enter your information in the form below:</legend>
    <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p>
    <p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p>
    <p><b>User Name:</b> <input type="text" name="username" size="20" maxlength="40" /></p>
    <p><b>Password:</b> <input type="password" name="password1" size="20" maxlength="40" /></p>
    <p><b>Confirm Password:</b> <input type="password" name="password2" size="20" 
    maxlength="40" /></p>
    </fieldset>
    <div align="center"><input type="submit" name="submit" value="Submit Information" /></div>
    </form>
    
    The form itself is fairly obvious and could certainly be expanded upon. Since the form is almost entirely HTML, I exit out of the PHP code, which is perfectly acceptable—even within a conditional. I'm also making use of the $PHP_SELF variable here, accessed through the $_SERVER superglobal. This variable will have the value of the current script's name. Placing it as the form's action will have the end result of having the form submit to itself.
  5. Complete the conditional and the PHP page.
    <?php
    } // End of the main SUBMIT conditional.
    include ('./footer.inc');
    ?>
    
    When going in and out of PHP, it's very easy to forget a curly brace, so I'd recommend using comments to mark your place.
  6. Save the file as register.php, upload to your Web server, and test in your Web browser ( Figures 3.14 , 3.15 , and 3.16 ).
    03fig14.gif

    Figure 3.14 The registration form...

    03fig15.gif

    Figure 3.15 ...and its successful completion.

    03fig16.gif

    Figure 3.16 If the form isn't filled out completely, error messages are generated.

Example 3.11. This page both displays and handles a registration form.

1   <?php # Script 3.11 - register.php
2
3   // Set the page title and include the HTML header.
4   $page_title = 'Register!';
5   include ('./header.inc');
6
7   if (isset($_POST['submit'])) { // Handle the form.
8
9       // Check for a name.
10      if (strlen($_POST['name']) > 0) {
11      $name = TRUE;
12      } else {
13          $name = FALSE;
14          echo '<p>You forgot to enter your name!</p>';
15     }
16
17      // Check for an email address.
18      if (strlen($_POST['email']) > 0) {
19          $email = TRUE;
20      } else {
21          $email = FALSE;
22          echo '<p>You forgot to enter your email address!</p>';
23      }
24
25      // Check for a username.
26      if (strlen($_POST['username']) > 0) {
27          $username = TRUE;
28      } else {
29         $username = FALSE;
30         echo '<p>You forgot to enter your user name!</p>';
31      }
32
33      // Check for a password and match against the confirmed password.
34      if (strlen($_POST['password1']) > 0) {
35          if ($_POST['password1'] == $_POST['password2']) {
36                  $password = TRUE;
37      } else {
38          $password = FALSE;
39      echo '<p>Your password did not match the confirmed password!</p>';
40      }
41  } else {
42          $password = FALSE;
43          echo '<p>You forgot to enter your password!</p>';
44      }
45
46      if ($name && $email && $username && $password) { // If everything's okayOK.
47          // Register the user.
48          echo '<p>You are now registered.</p>';
49      } else { // Something's not TRUE.
50          echo '<p>Please go back and try again.</p>';
51      }
52
53  } else { // Display the form.
54  ?>
55
56  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
57  <fieldset><legend>Enter your information in the form below:</legend>
58
59  <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p>
60
61  <p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p>
62
63  <p><b>User Name:</b> <input type="text" name="username" size="20" maxlength="40" /></p>
64
65  <p><b>Password:</b> <input type="password" name="password1" size="20" maxlength="40" /></p>
66
67  <p><b>Confirm Password:</b> <input type="password" name="password2" size="20" 
maxlength="40" /></p>
68  </fieldset>
69
70  <div align="center"><input type="submit" name="submit" value="Submit Information" /> <
/div>
71
72  </form><!-- End of Form -->
73
74  <?php
75  } // End of the main SUBMIT conditional.
76  include ('./footer.inc'); // Include the HTML footer.
77  ?>
  • + Share This
  • 🔖 Save To Your Account