Skip to content

php_ref_filter

The Filter extension is a crucial tool for modern PHP development, designed to validate and sanitize data, especially data coming from external sources like user input, forms, cookies, web services, or even database results. Proper data filtering is essential for security and application stability.

Key Use Cases:

  • Validation: Checking if data conforms to expected formats (e.g., is it a valid email address, integer, URL?).
  • Sanitization: Cleaning data by removing or encoding potentially harmful characters (e.g., removing HTML tags to prevent XSS, stripping characters illegal in a URL).

Never trust external data! Always validate and/or sanitize it before using it in your application.

The Filter extension is enabled by default as of PHP 5.2.0 and is part of the PHP core. No separate installation is typically required.

While explicit filtering using functions like filter_input() or filter_var() is the recommended practice, some php.ini settings can affect default filtering behavior (though modifying these is generally discouraged):

NameDescriptionDefaultChangeable
filter.defaultApplies a specified filter by default to all data from $_GET, $_POST, $_COOKIE, $_REQUEST, and $_SERVER. Accepts a filter name (e.g., string, email). Using this is generally discouraged in favor of explicit filtering.”unsafe_raw” (no filtering)PHP_INI_PERDIR
filter.default_flagsDefault flags to apply when filter.default is set. See filter flag constants below.null (was FILTER_FLAG_NO_ENCODE_QUOTES for legacy reasons)PHP_INI_PERDIR

Modern Best Practice: Avoid relying on filter.default. Always explicitly filter input where it is processed using filter_input(), filter_var(), or related functions.

FunctionDescription
filter_has_var()Checks if a variable of a specified type (INPUT_GET, INPUT_POST, etc.) exists.
filter_id()Returns the filter ID belonging to a named filter.
filter_input()Gets a specific external variable (e.g., from form input, server variables) by name and optionally filters it. Preferred method for accessing single input values.
filter_input_array()Gets multiple external variables and optionally filters them. Useful for processing multiple form fields at once.
filter_list()Returns a list of all supported filter names.
filter_var()Filters a variable that already exists in your script with a specified filter.
filter_var_array()Gets multiple variables already in your script and filters them.

PHP Predefined Filter Constants (Commonly Used)

Section titled “PHP Predefined Filter Constants (Commonly Used)”

These constants are used with filter functions to specify the type of validation or sanitization.

Validation Filters (Check if data matches criteria):

Section titled “Validation Filters (Check if data matches criteria):”
ConstantIDDescription
FILTER_VALIDATE_BOOLEAN258Validates value as boolean. Returns true for “1”, “true”, “on”, “yes”. Returns false for “0”, “false”, “off”, “no”, "". Returns null for non-boolean values if FILTER_NULL_ON_FAILURE flag is used, otherwise false.
FILTER_VALIDATE_DOMAIN277Validates whether the value is a valid domain name (according to RFCs).
FILTER_VALIDATE_EMAIL274Validates whether the value is a valid e-mail address.
FILTER_VALIDATE_FLOAT259Validates value as float. Allows optional fractional part and exponent.
FILTER_VALIDATE_INT257Validates value as integer. Allows optional sign, octal, hex prefixes.
FILTER_VALIDATE_IP275Validates value as IP address (IPv4 or IPv6). Use flags like FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 for specific versions.
FILTER_VALIDATE_MAC276Validates value as MAC address.
FILTER_VALIDATE_REGEXP272Validates value against a Perl-compatible regular expression (using the options parameter).
FILTER_VALIDATE_URL273Validates value as URL (according to RFC 2396). Checks for scheme presence (like http, ftp).

Sanitization Filters (Modify data to make it safe):

Section titled “Sanitization Filters (Modify data to make it safe):”
ConstantIDDescription
FILTER_SANITIZE_EMAIL517Removes all characters except letters, digits and !#$%&'*+-/=?^_{|}~@.[]`.
FILTER_SANITIZE_ENCODED514URL-encodes string, optionally strips or encodes special characters.
FILTER_SANITIZE_NUMBER_FLOAT520Removes all characters except digits, +, -, and optionally ., ,, e, E (flags can control allowed separators/exponents).
FILTER_SANITIZE_NUMBER_INT519Removes all characters except digits, +, -.
FILTER_SANITIZE_SPECIAL_CHARS515HTML-escapes special characters ('"<>& and characters with ASCII value < 32). Equivalent to calling htmlspecialchars().
FILTER_SANITIZE_URL518Removes all characters except letters, digits and $-_.+!*'(),{}|\^~[]”;/?:@=&`.
FILTER_UNSAFE_RAW516No sanitization occurs. Can be combined with flags like FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP.
ConstantStatusAlternative
FILTER_SANITIZE_MAGIC_QUOTESDeprecated/Removed (as Magic Quotes are removed)No direct replacement needed (as magic quotes shouldn’t be relied upon). Use appropriate DB escaping (prepared statements).
FILTER_SANITIZE_STRING / FILTER_SANITIZE_STRIPPEDDeprecated in PHP 8.0, Removed in PHP 8.1Use htmlspecialchars() for HTML output, or other specific sanitization/validation as needed. Do not use this filter for security.
ConstantIDDescription
FILTER_CALLBACK1024Calls a custom user-defined function to filter data.

Flags modify the behavior of filters (e.g., FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_STRIP_LOW, FILTER_NULL_ON_FAILURE). Consult the PHP manual for a full list: https://www.php.net/manual/en/filter.filters.flags.php

<?php
declare(strict_types=1);
// Example: Sanitize user input for HTML display
$unsafe_comment = "<script>alert('xss');</script> This is a comment.";
$safe_comment = filter_var($unsafe_comment, FILTER_SANITIZE_SPECIAL_CHARS);
echo $safe_comment; // Output: &lt;script&gt;alert(&#039;xss&#039;);&lt;/script&gt; This is a comment.
echo "<br>";
// Example: Validate an email address from POST data
$email = filter_input(INPUT_POST, 'user_email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
echo "Invalid email address provided.";
} elseif ($email === null) {
echo "Email address not provided.";
} else {
echo "Valid email: " . htmlspecialchars($email, ENT_QUOTES, 'UTF-8');
}
?>

For detailed information and more examples, see the official PHP documentation: https://www.php.net/manual/en/book.filter.php