PHP Filters

Validating data = Determine if the data is in proper form. Sanitizing data = Remove any illegal character from the data.

The PHP Filter Extension

PHP filters are used to validate and sanitize external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker. The filter_list() function can be used to list what the PHP filter extension offers:

Example -

PHP filter_var() Function

The filter_var() function both validate and sanitize data. The filter_var() function filters a single variable with a specified filter. It takes two pieces of data:

  • The variable you want to check
  • The type of check to use
  • Sanitize a String

    The following example uses the filter_var() function to remove all HTML tags from a string:

    Example -

    Validate an Integer

    Example -

    Validate an IP Address

    The following example uses the filter_var() function to check if the variable $ip is a valid IP address:

    Example -

    Sanitize and Validate an Email Address

    The following example uses the filter_var() function to first remove all illegal characters from the $email variable, then check if it is a valid email address:

    Example -