Validating Form Data


A critical concept related to handling HTML forms is that of validating form data. In terms of both error management and security, you should absolutely never trust the data being entered in an HTML form. Whether erroneous data is purposefully malicious or just unintentionally inappropriate, it's up to youthe Web architectto test it against expectations.

Validating form data requires the use of conditionals and any number of functions, operators, and expressions. One common function to be used is isset(), which tests if a variable has a value (including 0, FALSE, or an empty string, but not NULL).

 if (isset($var)) {    // $var has a value. } else {    // $var does not have a value. } 

You saw an example of this in the preceding script.

One problem with the isset() function is that an empty string tests as trUE, meaning that it's not an effective way to validate text inputs and text boxes from an HTML form. To check that a user typed something into textual elements like name, email, and comments, you can use the empty() function. It checks if a variable has an empty value: an empty string, 0, NULL, or FALSE.

The first aim of form validation is ensuring that something was entered or selected in form elements. The second goal is to ensure that submitted data is of the right type (numeric, string, etc.), of the right format (like an email address), or a specific acceptable value (like $gender being equal to either M or F). As handling forms is a main use of PHP, validating form data is a point that will be re-emphasized time and again in subsequent chapters.. At this point, I'll write a new handle_form.php script that makes sure variables have values before they're referenced.

To validate your forms

1.

Begin a new PHP script in your text editor (Script 2.5).

 <!DOCTYPE html PUBLIC "-//W3C//  DTD XHTML 1.0 Transitional//EN "http://www.w3.org/TR/xhtml1/DTD/  xhtml1-transitional.dtd> <html xmlns="http://www.w3.org/1999/  xhtml xml:lang="en" lang="en"> <head>   <meta http-equiv="content-type"     content="text/html;    charset=iso-8859-1 />   <title>Form Feedback</title> </head> <body> <?php # Script 2.5 - handle_form.php   (4th version after Scripts 2.2,   2.3, & 2.4) 

Script 2.5. Validating HTML form data before you use it is critical to Web security and achieving professional results.


2.

Check if the name was entered.

 if (!empty($_REQUEST['name'])) {   $name = stripslashes($_REQUEST    ['name]); } else {   $name = NULL;   echo '<p><font color="red">You     forgot to enter your    name!</font></p>'; } 

A simple way to check that a form text input was filled out is to use the empty() function. If $_REQUEST['name'] has a value other than an empty string, 0, NULL, or FALSE, I'll assume that their name was entered. If so, I'll strip the slashes from it as before to combat Magic Quotes. If the variable is empty, I'll set the $name variable to NULL and print an error message.

3.

Repeat the same process for the email address and comments.

 if (!empty($_REQUEST['email'])) {   $email = $_REQUEST['email']; } else {   $email = NULL;   echo '<p><font color="red">You    forgot to enter your email    address!</font></p>'; } if (!empty($_REQUEST['comments'])) {   $comments = stripslashes($_REQUEST    ['comments]); } else {   $comments = NULL;   echo '<p><font color="red">You    forgot to enter your comments!</    font></p>'; } 

The $comments variable receives the same treatment as $name in Step 2, while $email differs slightly, because I'm not applying the stripslashes() function to it.

4.

Check the status of the gender.

 if (isset($_REQUEST['gender'])) {   $gender = $_REQUEST['gender'];   if ($gender == 'M') {      $message = '<p><b>Good day,        Sir!</b></p>';   } elseif ($gender == 'F') {      $message = '<p><b>Good day,       Madam!</b></p>';   } else {      $message = NULL;      echo '<p><font color="red">Gender should be either  "M or "F"!</font></p>';   } } else {   $gender = NULL;   echo '<p><font color="red">You     forgot to select your gender!</    font></p>'; } 

The validation of the gender is a two-step process. First, I check if it has a value or not, using isset(). This is the main if-else conditional, which otherwise behaves like those for the name, email address, and comments. Within the if clause is some extra code that performs a validation on gender, testing it against the acceptable values. If gender does not end up being equal to either M or F, a problem occurred and an error message is printed. The $gender variable is also set to NULL in such cases, because it has an unacceptable value.

In previous scripts (refer to Script 2.4 and Figures 2.8, 2.9, and 2.10), I printed out a gender-specific message at the bottom of the page. Since I haven't yet printed out the initial Thank you message at this point in the script, I'll create a $message variable instead, which will be printed later.

5.

Print the messages if all of the tests have been passed.

 if ($name && $email && $gender &&  $comments) {   echo "<p>Thank you, <b>$name</b>,    for the following comments:<br />   <tt>$comments</tt></p>   <p>We will reply to you at    <i>$email</i>.</p>\n;   echo $message; } else {   echo '<p><font color="red">Please    go back and fill out the form    again.</font></p>'; } 

This main condition is true if every listed variable has a non-NULL value. Each variable will have a value if it passed its test but have a value of NULL if it didn't. If every variable has a value, the form was completed, so the Thank you and gender-specific messages will be printed. If any of the variables are NULL, the second message will be printed.

6.

Close the PHP section and complete the HTML code.

 ?> </body> </html> 

7.

Save the file as handle_form.php, upload to your Web server in the same directory as form.html, and test in your Web browser (Figures 2.11, 2.12, and 2.13).

Figure 2.11. The script now checks that every form element was filled out (except the age) and reports on those that weren't.


Figure 2.12. If even one or two fields were skipped, the Thank you message is not printed…


Figure 2.13. …but if everything was entered properly, the script behaves as it previously had.


Fill out the form to different levels of completeness to test the new script.

Tips

  • To test if a submitted value is a number, use the is_numeric() function.

  • In Chapter 10, "Web Application Security," you'll see how to validate form data using JavaScript on the client side as well as regular expressions on the server side.

  • The $age variable is still not used or validated for the sake of saving book space. To validate it, repeat the $gender validation routine, referring to $_REQUEST['age'] instead. To test $age's specific value, use an if-elseif-elseif-else, checking against the corresponding pull-down options (0-29, 30-60, 60+).

  • It's considered good form (pun intended) to let a user know which fields are required when they're filling out the form, and where applicable, the format of that field (like a date or a phone number).

  • Another way of validating text inputs is to use the strlen() function to see if more than zero characters were typed.

     if (strlen($var) > 0) {    // $var has a value. } else {    // $var does not have a value. } 




    PHP and MySQL for Dynamic Web Sites. Visual QuickPro Guide
    PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)
    ISBN: 0321336577
    EAN: 2147483647
    Year: 2005
    Pages: 166
    Authors: Larry Ullman

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net