| home / programming / php / php5-advanced2 |
|
|
The script has one CSS class for printing errors in a different color.
Script 4.2. With this minimalist registration form, the Filter library is used to perform data validation and sanitization.
For the name field, there's no type to validate against, but it can be filtered to remove any HTML tags. The FILTER_SANITIZE_STRING filter will accomplish that. The last argument, FILTER_FLAG_NO_ENCODE_QUOTES, says that any quotation marks in the name (e.g., O'Toole) shouldn't be turned into an HTML entity equivalent.
The conditional if ($name) will be true if the $_POST['name'] variable was set and passed the filter. In that case, I'll print the filtered version and the original version, just for comparison.
The FILTER_VALIDATE_EMAIL filter is perfect here. If the submitted email address has a valid format, it will be returned. Otherwise, $email will equal either FALSE or NULL.
This is validated as an integer.
For the comments, any tags will be stripped (as with the name), but the quotation marks will also be encoded.
filter.php, place it in your Web directory, and test in your Web browser (Figures 4.5 and 4.6).

Figure 4.5 These values will be submitted, then filtered, resulting in Figure 4.6.

Figure 4.6 At the top of the form the filtered values are displayed.

Figure 4.7 The HTMLsource code shows how all tags are stripped from the name and comments fields, plus how quotation marks in the comments are encoded.
filter_has_var() function checks to see if a variable with a given name exists within a greater array of variables. In this script, you could use this code to see if the form has been submitted:
To filter an array of variables, use filter_input_array(). In filter.php, you could just do this:
From that point, you could just refer to $data['name'], etc.
filter_var_array() applies a filter, or an array of filters, to an array of data.| home / programming / php / php5-advanced2 |
URL: