php_ref_filter
PHP Filter Extension
Section titled “PHP Filter Extension”PHP Filter Introduction
Section titled “PHP Filter Introduction”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.
Installation
Section titled “Installation”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.
Runtime Configuration (php.ini)
Section titled “Runtime Configuration (php.ini)”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):
| Name | Description | Default | Changeable |
|---|---|---|---|
filter.default | Applies 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_flags | Default 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.
PHP Filter Functions
Section titled “PHP Filter Functions”| Function | Description |
|---|---|
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):”| Constant | ID | Description |
|---|---|---|
FILTER_VALIDATE_BOOLEAN | 258 | Validates 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_DOMAIN | 277 | Validates whether the value is a valid domain name (according to RFCs). |
FILTER_VALIDATE_EMAIL | 274 | Validates whether the value is a valid e-mail address. |
FILTER_VALIDATE_FLOAT | 259 | Validates value as float. Allows optional fractional part and exponent. |
FILTER_VALIDATE_INT | 257 | Validates value as integer. Allows optional sign, octal, hex prefixes. |
FILTER_VALIDATE_IP | 275 | Validates value as IP address (IPv4 or IPv6). Use flags like FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 for specific versions. |
FILTER_VALIDATE_MAC | 276 | Validates value as MAC address. |
FILTER_VALIDATE_REGEXP | 272 | Validates value against a Perl-compatible regular expression (using the options parameter). |
FILTER_VALIDATE_URL | 273 | Validates 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):”| Constant | ID | Description |
|---|---|---|
FILTER_SANITIZE_EMAIL | 517 | Removes all characters except letters, digits and !#$%&'*+-/=?^_{|}~@.[]`. |
FILTER_SANITIZE_ENCODED | 514 | URL-encodes string, optionally strips or encodes special characters. |
FILTER_SANITIZE_NUMBER_FLOAT | 520 | Removes all characters except digits, +, -, and optionally ., ,, e, E (flags can control allowed separators/exponents). |
FILTER_SANITIZE_NUMBER_INT | 519 | Removes all characters except digits, +, -. |
FILTER_SANITIZE_SPECIAL_CHARS | 515 | HTML-escapes special characters ('"<>& and characters with ASCII value < 32). Equivalent to calling htmlspecialchars(). |
FILTER_SANITIZE_URL | 518 | Removes all characters except letters, digits and $-_.+!*'(),{}|\^~[]”;/?:@=&`. |
FILTER_UNSAFE_RAW | 516 | No 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. |
Deprecated/Removed Filters:
Section titled “Deprecated/Removed Filters:”| Constant | Status | Alternative |
|---|---|---|
FILTER_SANITIZE_MAGIC_QUOTES | Deprecated/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_STRIPPED | Deprecated in PHP 8.0, Removed in PHP 8.1 | Use htmlspecialchars() for HTML output, or other specific sanitization/validation as needed. Do not use this filter for security. |
Other Filters:
Section titled “Other Filters:”| Constant | ID | Description |
|---|---|---|
FILTER_CALLBACK | 1024 | Calls a custom user-defined function to filter data. |
Filter Flags:
Section titled “Filter Flags:”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
Example:
Section titled “Example:”<?phpdeclare(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: <script>alert('xss');</script> 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');}?>Further Reading:
Section titled “Further Reading:”For detailed information and more examples, see the official PHP documentation: https://www.php.net/manual/en/book.filter.php