(PHP 5 >= 5.2.0, PHP 7, PHP 8)
filter_id — Returns the filter ID belonging to a named filter
Parameters
name-
Name of a filter to get.
Return Values
ID of a filter on success or false if filter doesn't exist.
0
masakielastic at gmail dot com ¶
1 month ago
The names accepted by filter_id() are names of filters provided by the filter extension. They should not be treated as general-purpose validation rule names.
For example, "validate_email" is a validation filter, while "email" is a sanitization filter:
<?php
var_dump(filter_id('validate_email') === FILTER_VALIDATE_EMAIL); // bool(true)
var_dump(filter_id('email') === FILTER_SANITIZE_EMAIL); // bool(true)
var_dump(filter_var('not an email', filter_id('validate_email'))); // bool(false)
var_dump(filter_var('not an email', filter_id('email'))); // string(10) "notanemail"
?>
This distinction matters when filter names come from configuration or a schema. If only validation is intended, consider using an application-level allow-list instead of passing arbitrary names directly to `filter_id()`:
<?php
function validation_filter_id(string $name): int
{
return match ($name) {
'email' => FILTER_VALIDATE_EMAIL,
'url' => FILTER_VALIDATE_URL,
'int' => FILTER_VALIDATE_INT,
'float' => FILTER_VALIDATE_FLOAT,
'bool', 'boolean' => FILTER_VALIDATE_BOOLEAN,
'ip' => FILTER_VALIDATE_IP,
'domain' => FILTER_VALIDATE_DOMAIN,
'mac' => FILTER_VALIDATE_MAC,
'regexp' => FILTER_VALIDATE_REGEXP,
default => throw new InvalidArgumentException(
"Unknown validation filter: {$name}"
),
};
}
$filter = validation_filter_id('email');
var_dump(filter_var('user@example.com', $filter)); // string(16) "user@example.com"
var_dump(filter_var('not an email', $filter)); // bool(false)
?>0
15 years ago
[To get a list of filters and their IDs:]
<?php
$filters = filter_list();
foreach($filters as $filter_name) {
echo $filter_name .": ".filter_id($filter_name) ."<br>";
}
?>
Will result in:
boolean: 258
float: 259
validate_regexp: 272
validate_url: 273
validate_email: 274
validate_ip: 275
string: 513
stripped: 513
encoded: 514
special_chars: 515
unsafe_raw: 516
email: 517
url: 518
number_int: 519
number_float: 520
magic_quotes: 521
callback: 1024