PHP 5 Advanced: Visual QuickPro Guide/Page 2 | WebReference

PHP 5 Advanced: Visual QuickPro Guide/Page 2

[previous] [next]

Security Techniques: Part 2

To use PECL Filter

  1. 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.

  2. Check for the form submission.

  3. 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_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.

  4. Print the name value or an error.

    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.

  5. Validate the email address.

    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.

  6. Validate the ICQ number.

    This is validated as an integer.

  7. Filter the comments field.

    For the comments, any tags will be stripped (as with the name), but the quotation marks will also be encoded.

  8. Complete the main conditional and the PHP code.

  9. Create the HTML form.

  10. Complete the page.

  11. 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.

  12. 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.

[previous] [next]