PHP 8.5.8 Released!

filter_id

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_idRetourne l'identifiant d'un filtre nommé

Description

function filter_id(string $name): int|false

Liste de paramètres

name

Nom du filtre à récupérer.

Valeurs de retour

Identifiant du filtre en cas de succès, ou false si le filtre n'existe pas.

Voir aussi

  • filter_list() - Retourne une liste de tous les filtres supportés
add a note

User Contributed Notes 2 notes

up
0
masakielastic at gmail dot com
3 hours 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)

?>
up
0
w0n4b3 at gmail dot com
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
To Top