The PHP filter extension checks and cleans data that comes from users or other outside sources. It can validate a value (is this a real email, an integer, a URL?) or sanitize it (remove characters you do not want).
Two functions do most of the work: filter_var() filters a value you already have, and filter_input() reads a value from $_GET, $_POST, $_COOKIE, $_SERVER, or $_ENV and filters it in one step. Both use FILTER_* constants to choose the rule.
This page explains the ideas. The Filter Functions index lists all seven function guides.
Validate first.
FILTER_VALIDATE_* returns the value on success and false on failure, so you can reject bad input. FILTER_SANITIZE_* changes the value instead of rejecting it.
Filtering is not escaping.
A valid email can still hold characters that matter in HTML or SQL. Escape on output with htmlspecialchars() and use prepared statements for databases.
Syntax
PHP Syntax
The two common entry points:
PHP
// Filter a value you already have
$result = filter_var($value, FILTER_VALIDATE_EMAIL);
// Read from an input source and filter in one step
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
// $result / $page:
// the filtered value on success
// false when validation fails
// null (filter_input only) when the variable is not set
The filter extension is a built-in set of functions and FILTER_* constants that validate and sanitize data. You can check that a value is a valid email, integer, URL, IP address, or boolean, or strip unwanted characters from it before you use it.
Validating (FILTER_VALIDATE_*) checks whether a value is acceptable and returns the value or false. Sanitizing (FILTER_SANITIZE_*) changes the value by removing or encoding characters. Validate when you want to reject bad input; sanitize when you must keep the input but make it safe for a given use.
Use filter_var() for any value you already hold in a variable. Use filter_input() to read and filter a value straight from GET, POST, COOKIE, SERVER, or ENV in one step. filter_input() returns null when the variable is missing and false when the filter fails.
No. FILTER_SANITIZE_STRING and FILTER_SANITIZE_STRIPPED are deprecated since PHP 8.1. Use FILTER_SANITIZE_SPECIAL_CHARS or htmlspecialchars() when you output text in HTML, and prepared statements for databases.
Practice the examples here, then open the Filter Functions index for all seven function guides, from filter_has_var() to filter_var_array().