PHP 5 Advanced: Visual QuickPro Guide/Page 2
Security Techniques: Part 2
To use PECL Filter
- Begin a new PHP script in your text editor or IDE, starting with the HTML (Script 4.2).
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.
- Check for the form submission.
- Filter the name data.
For the name field, there's no type to validate against, but it can be filtered to remove any HTML tags. The
FILTER_SANITIZE_STRINGfilter 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.
- Print the name value or an error.
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.
- Validate the email address.
FILTER_VALIDATE_EMAILfilter is perfect here. If the submitted email address has a valid format, it will be returned. Otherwise,
- Validate the ICQ number.
This is validated as an integer.
- Filter the comments field.
For the comments, any tags will be stripped (as with the name), but the quotation marks will also be encoded.
- Complete the main conditional and the PHP code.
- Create the HTML form.
- Complete the page.
- Save the file as
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.
- View the HTML source of the page to see how the name and comments fields were treated (Figure 4.7).
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.php, you could just do this:
From that point, you could just refer to
filter_var_array()applies a filter, or an array of filters, to an array of data.