Filtres de validation

Liste des filtre de validation
ID Nom Options Flags Description
FILTER_VALIDATE_BOOLEAN "boolean" default FILTER_NULL_ON_FAILURE

Retourne TRUE pour "1", "true", "on" et "yes". Retourne FALSE sinon.

Si FILTER_NULL_ON_FAILURE est active, FALSE n'est retourné que pour les valeurs "0", "false", "off", "no", "", et NULL est retourné pour les valeurs non-booléennes.

FILTER_VALIDATE_EMAIL "validate_email" default  

Valide une adresse de courriel.

En général, ceci valide l'adresse de courriel selon la syntaxe défini par la RFC 822, à l'exception des commentaires et du remplissage par des espaces qui ne sont pas supportés.

FILTER_VALIDATE_FLOAT "float" default, decimal FILTER_FLAG_ALLOW_THOUSAND Valide un nombre décimal.
FILTER_VALIDATE_INT "int" default, min_range, max_range FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX Valide un entier, éventuellement dans un intervalle donné.
FILTER_VALIDATE_IP "validate_ip" default FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE Valide une adresse IP, éventuellement IPv4 ou IPv6, éventuellement hors des plages privées ou réservées.
FILTER_VALIDATE_MAC "validate_mac_address" default   Valide la valeur comme une adresse MAC.
FILTER_VALIDATE_REGEXP "validate_regexp" default, regexp   Valide une valeur avec une expression rationnelle regexp, compatible Perl.
FILTER_VALIDATE_URL "validate_url" default FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED Valide une URL (selon » http://www.faqs.org/rfcs/rfc2396), éventuellement avec des composants requis. Attention, une URL valide peut ne pas spécifier le protocole HTTP http://, aussi, des validations ultérieures supplémentaires seront requises pour déterminer si l'URL utilise un protocole attendu, i.e. ssh:// ou mailto:. Cette fonction ne trouvera que des URLs ASCII valides, les domaines internationnalisés (contenant des caractères non-ASCII) ne fonctionneront pas.

Note:

Depuis PHP 5.4.11, les nombres +0 et -0 sont validées comme des entiers, mais aussi comme des nombres à virgule flottante (en utilisant les constantes FILTER_VALIDATE_FLOAT et FILTER_VALIDATE_INT). Avant PHP 5.4.11, ils n'étaient validés que comme des nombres à virgule flottante (en utilisant la constante FILTER_VALIDATE_FLOAT).

Lorsque le paramètre default est défini comme option, la valeur passée est utilisée si la valeur n'est pas validée.

Historique

Version Description
5.5.0 Ajout de la constante FILTER_VALIDATE_MAC

add a note add a note

User Contributed Notes 16 notes

up
22
boy at relaxnow dot nl
2 years ago
FILTER_VALIDATE_URL does not work with URNs, examples of valid URIs according to RFC3986 and if they are accepted by FILTER_VALIDATE_URL:

[PASS] ftp://ftp.is.co.za.example.org/rfc/rfc1808.txt
[PASS] gopher://spinaltap.micro.umn.example.edu/00/Weather/California/Los%20Angeles
[PASS] http://www.math.uio.no.example.net/faq/compression-faq/part1.html
[PASS] mailto:mduerst@ifi.unizh.example.gov
[PASS] news:comp.infosystems.www.servers.unix
[PASS] telnet://melvyl.ucop.example.edu/
[PASS] http://www.ietf.org/rfc/rfc2396.txt
[PASS] ldap://[2001:db8::7]/c=GB?objectClass?one
[PASS] mailto:John.Doe@example.com
[PASS] news:comp.infosystems.www.servers.unix
[FAIL] tel:+1-816-555-1212
[PASS] telnet://192.0.2.16:80/
[FAIL] urn:oasis:names:specification:docbook:dtd:xml:4.1.2
up
8
Bastien
1 year ago
Rejection of so-called partial domains because of "missing" dot is not following section 2.3.5 of RFC 5321.

It says FQDNs are permitted, and com, org, or va are (well, may be) valids FQDNs. It depends on DNS, not on syntax.

Some TDLs (although few of them) have MX RRs, the for example "abuse@va" is correct.
up
14
bee kay two at em ee dot com
3 years ago
Notably missing is a way to validate text entry as printable,
printable multiline,
or printable and safe (tag free)

FILTER_VALIDATE_TEXT, which validates no special characters
perhaps with FILTER_FLAG_ALLOW_NEWLINE
and FILTER_FLAG_NOTAG to disallow tag starters
up
8
Clifton
4 years ago
FILTER_VALIDATE_EMAIL does NOT allow incomplete e-mail addresses to be validated as mentioned by Tomas.

Using the following code:

<?php
$email
= "clifton@example"; //Note the .com missing
echo "PHP Version: ".phpversion().'<br>';
if(
filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo
$email.'<br>';
   
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
   
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));   
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
bool(false)

While the following code:

<?php
$email
= "clifton@example.com"; //Note the .com added
echo "PHP Version: ".phpversion().'<br>';
if(
filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo
$email.'<br>';
   
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
   
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));   
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
clifton@example.com
string(16) "clifton@example.com"

This feature is only available for PHP Versions (PHP 5 >= 5.2.0) according to documentation. So make sure your version is correct.

Cheers,
Clifton
up
6
rowan dot collins at gmail dot com
2 years ago
Regarding "partial" addresses with no . in the domain part, a comment in the source code (in ext/filter/logical_filters.c) justifies this rejection thus:

     * The regex below is based on a regex by Michael Rushton.
     * However, it is not identical.  I changed it to only consider routeable
     * addresses as valid.  Michael's regex considers a@b a valid address
     * which conflicts with section 2.3.5 of RFC 5321 which states that:
     *
     *   Only resolvable, fully-qualified domain names (FQDNs) are permitted
     *   when domain names are used in SMTP.  In other words, names that can
     *   be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed
     *   in Section 5) are permitted, as are CNAME RRs whose targets can be
     *   resolved, in turn, to MX or address RRs.  Local nicknames or
     *   unqualified names MUST NOT be used.
up
3
php dot net at piskvor dot org
4 years ago
FILTER_VALIDATE_EMAIL is discarding valid e-mail addresses containing IDN. Since there are real, live IDNs on the Internet, that means the filtered output is too strict, leading to false negatives.

Punycode-encoded IDN addresses pass the filter correctly; so before checking for validity, it is necessary to convert the e-mail address to punycode.
up
1
Luuk
2 months ago
@2:
$value = " 0 ";
$filtered = filter_var($value, FILTER_VALIDATE_INT);
if($filtered || $filtered === 0)
{
    // validated as an int
}

I think next code is better:

$value = "0";
if(filter_var($value, FILTER_VALIDATE_INT) !== false)
{
  .....
up
0
Wrinkled Cheese
1 month ago
When validating a URL, as documented, the protocol is not validated.  However, it is required to be present.

For example:

I don't expect a protocol to be present.  To validate expected input I have to add a "protocol" as a prefix, and return true or false, and further validate the input.

$r = filter_var(''this.doesnt.matter.so.why.is.it.required://'.$host, FILTER_VALIDATE_URL);
return ($r != '' && $r !== false) ? true : false;
up
0
Darth Killer
2 months ago
Contrary to what documentation implies, the FILTER_NULL_ON_FAILURE seem to affect any validation filter, not just FILTER_VALIDATE_BOOLEAN. I've been using that since PHP 5.2, and as of PHP 5.6.8 it still works. I have no clue if it's a blug or if it is as intended, in which case the documentation needs to be fixed.

When the flag is used on a validation filter other than FILTER_VALIDATE_BOOLEAN, as expected the filter will return NULL instead of FALSE upon failure. This is quite useful when filtering a POST form with filter_input_array(), where you don't want to check what field is invalid and what field is missing. Just check if NULL is among the returned elements and you're done.

<?php
$definition
= array(
  
'login' => array(
     
'filter' => FILTER_VALIDATE_STRING,
     
'flags' => FILTER_NULL_ON_FAILURE
  
),
  
'pwd' => FILTER_UNSAFE_RAW
);
$form_data = filter_input_array(INPUT_POST, $definition);
if(
in_array(null, $form_data, true)) {
  
// invalid form
} else {
  
// valid form, let's proceed
}
?>

Of course, if you want more precise error messages that approach won't work. But it's still good to know, i believe.
up
0
Anonymous
2 months ago
FILTER_VALIDATE_FLOAT, decimal option mean decimal notation['.', ','].
up
0
bryanwayb at gmail dot com
4 months ago
It's good to remember that using filter_var is primarily for filtering input values when doing boolean logic comparisons. Take the following:

$value = "12";
if(filter_var($value, FILTER_VALIDATE_INT))
{
    // validated as an int
}

The above works as intended, except when $value = "0". In which case filter_var returns a 0, aka false when used as a boolean.

For the correct behavior, do a zero check.

$value = " 0 ";
$filtered = filter_var($value, FILTER_VALIDATE_INT);
if($filtered || $filtered === 0)
{
    // validated as an int
}
up
0
php at sethsyberg dot com
4 years ago
When validating floats, you must use the Identical/Not identical operators for proper validation of zeros:

This will not work as expected:
<?php
$x
= 0;
if (!
filter_var($x, FILTER_VALIDATE_FLOAT)) {
    echo
"$x is a valid float";
} else {
    echo
"$x is NOT a valid float";
}
?>

This will work as expected:
<?php
$x
= 0;
if (
filter_var($x, FILTER_VALIDATE_FLOAT)!== false) {
    echo
"$x is a valid float";
} else {
    echo
"$x is NOT a valid float";
}
?>
up
-1
maruerru at gmail dot com
4 months ago
Often I see some code like the following:
$value = "12";
if( filter_var($value, FILTER_VALIDATE_INT) )
{
    // validated as an int
}

The above works as intended, except when $value is "0". In the above case it will be interpreted as FALSE.

For the correct behavior,  you have not only to check if it is equal (==) to false, but also identic (===) to FALSE:
$value = " 0 ";
if( filter_var($value, FILTER_VALIDATE_INT)  === FALSE )
{
    // validated as an int
}

I hope, I could help.
up
-5
chastell at chastell dot net
4 years ago
example@example is a perfectly valid email address – I use chastell@localhost and chastell@devielle (my computer’s name) email addresses all the time and they get delivered just fine.
up
-15
Tom
3 years ago
Be aware!

In contrary to what the docs say (at least in PHP 5.3.1), this line:

$value = filter_var(FALSE, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

Will return NULL - not false. In other words: a boolean FALSE is not considered a valid boolean value by this function.

Also:

$value = filter_var("", FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

Will also return NULL - no matter what the docs say. So (string) FALSE is not considered a valid boolean input either.

Thus be aware the that correct usage/workaround for this filter is:

if (!is_bool($value)) {
    $value= filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}

For those of you who feel this is counterintuitive, note that there is an issue filed for this in the bug-tracker.
So you might want to follow the discussion there or vote for issue #49510.
up
-16
Griff
3 years ago
<< FILTER_VALIDATE_EMAIL allows incomplete e-mail addresses to be validated, for examle john@gmail will validate as a proper e-mail address >>

"Plain" hostnames with no dots are valid in email addresses -
for example, "me@localhost".
To Top