PHP Filters

In PHP, filters are used to validate and sanitize external input (like from forms, URLs, etc.). The filter extension provides a range of filters to ensure data is safe and properly formatted before use.

Why Use PHP Filters?

  • Validation: Check if the data is of the expected type (e.g., email, integer).

  • Sanitization: Clean data by removing or encoding unwanted characters.


Common PHP Filter Functions

Function Description
filter_var() Filters a single variable with a specified filter.
filter_input() Gets an input variable and filters it.
filter_input_array() Gets multiple input variables and filters them.
filter_var_array() Filters multiple variables in an array.

Commonly Used Filters

Validation Filters

Filter Description
FILTER_VALIDATE_INT Validates an integer.
FILTER_VALIDATE_BOOLEAN Validates a boolean.
FILTER_VALIDATE_FLOAT Validates a float.
FILTER_VALIDATE_EMAIL Validates an email address.
FILTER_VALIDATE_URL Validates a URL.
FILTER_VALIDATE_IP Validates an IP address.

Sanitization Filters

Filter Description
FILTER_SANITIZE_STRING Removes tags and encodes special characters. (Deprecated in PHP 8.1)
FILTER_SANITIZE_EMAIL Removes all illegal email characters.
FILTER_SANITIZE_URL Removes all illegal URL characters.
FILTER_SANITIZE_NUMBER_INT Removes all characters except digits and +/-.
FILTER_SANITIZE_SPECIAL_CHARS Encodes special characters to HTML entities.

Examples

Validate an Email

$email = "user@example.com"; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid email."; } else { echo "Invalid email."; }

Sanitize a String

$dirty = "<h1>Hello</h1>"; $clean = filter_var($dirty, FILTER_SANITIZE_SPECIAL_CHARS); echo $clean; // Outputs: &lt;h1&gt;Hello&lt;/h1&gt;

Filter Input from a Form

$name = filter_input(INPUT_POST, "name", FILTER_SANITIZE_STRING);