Фильтры валидации данных

Список фильтров валидации данных
ID Имя Параметры Флаги Описание
FILTER_VALIDATE_BOOLEAN "boolean" default FILTER_NULL_ON_FAILURE

Возвращает TRUE для значений "1", "true", "on" и "yes". Иначе возвращает FALSE.

Если установлен флаг FILTER_NULL_ON_FAILURE, то FALSE возвращается только для значений "0", "false", "off", "no" и "", а NULL будет возвращен для всех не булевых значений.

FILTER_VALIDATE_EMAIL "validate_email" default   Проверяет, что значение является корректным e-mail.
FILTER_VALIDATE_FLOAT "float" default, decimal FILTER_FLAG_ALLOW_THOUSAND Проверяет, что значение является корректным числом с плавающей точкой.
FILTER_VALIDATE_INT "int" default, min_range, max_range FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX Проверяет, что значение является корректным целым числом, и, при необходимости, входит в определенный диапазон.
FILTER_VALIDATE_IP "validate_ip" default FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE Проверяет, что значение является корректным IP-адресом, при необходимости только для протоколов IPv4 или IPv6, а также отсутствие вхождения в частные или зарезервированные диапазоны.
FILTER_VALIDATE_REGEXP "validate_regexp" default, regexp   Проверяет значение на соответствие regexp, Perl-совместимому регулярному выражению.
FILTER_VALIDATE_URL "validate_url" default FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED Проверяет значение на корректность URL (в соответствии с » http://www.faqs.org/rfcs/rfc2396), при желании можно указать обязательные компоненты. Имейте в виду, что корректная ссылка может не содержать HTTP-протокол http://, т.е. необходима еще одна проверка, определяющая наличие необходимого протокола у ссылки, например, ssh:// или mailto:. Обратите внимание, что функция работает только с ASCII-ссылками, таким образом, интернациональные доменные имена (содержащие не-ASCII символы) не пройдут проверку.

Замечание:

Начиная с PHP 5.4.11, числа +0 и -0 проверяются оба и как целые, и как числа с плавающей точкой (используя FILTER_VALIDATE_FLOAT и FILTER_VALIDATE_INT). До версии PHP 5.4.11 они проверялись только как числа с плавающей точкой (FILTER_VALIDATE_FLOAT).

Если установлен параметр default, то значение defaultиспользуется, если не прошла валидация.

Коментарии

Автор:
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($emailFILTER_VALIDATE_EMAIL)){
    echo 
$email.'<br>';
   
var_dump(filter_var($emailFILTER_VALIDATE_EMAIL));
}else{
   
var_dump(filter_var($emailFILTER_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($emailFILTER_VALIDATE_EMAIL)){
    echo 
$email.'<br>';
   
var_dump(filter_var($emailFILTER_VALIDATE_EMAIL));
}else{
   
var_dump(filter_var($emailFILTER_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
2011-01-05 10:00:01
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
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.
2011-02-11 10:57:46
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
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($xFILTER_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($xFILTER_VALIDATE_FLOAT)!== false) {
    echo 
"$x is a valid float";
} else {
    echo 
"$x is NOT a valid float";
}
?>
2011-04-07 16:00:18
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
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
2012-05-06 07:45:29
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
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
2012-10-19 17:06:13
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
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.
2013-03-17 22:22:28
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
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.
2013-09-24 11:05:01
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
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
}
2015-03-22 06:18:04
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
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.
2015-03-27 01:09:01
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
FILTER_VALIDATE_FLOAT, decimal option mean decimal notation['.', ','].
2015-05-22 11:02:19
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
@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)
{
  .....
2015-05-25 13:23:21
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
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_datatrue)) {
   
// 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.
2015-06-02 11:54:06
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
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;
2015-06-09 18:33:54
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
The description for FILTER_VALIDATE_URL seems incorrect/misleading. "Beware a valid URL may not specify the HTTP protocol" implies a valid URL cannot specify the HTTP protocol. I think "Beware a valid URL need not specify..." would be better.
2015-09-05 23:41:31
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Note that if using FILTER_NULL_ON_FAILURE as a flag with the FILTER_VALIDATE_BOOLEAN id then NULL is no longer returned if the variable name is not set in the external variable array. It will instead return FALSE. In the description is says that when using the FILTER_NULL_ON_FAILURE flag that ' FALSE is returned only for "0", "false", "off", "no", and ""' an makes no mention of this additional state that can also return false. The behavior is mentioned on the filter_input documentation page under Return Values but that is not overly helpful if one is just looking here.

If FILTER_NULL_ON_FAILURE is not used then NULL is returned when the variable name is not set in the external variable array, TRUE is returned for "1", "true", "on" and "yes" and FALSE is returned for everything else.
2015-11-25 19:18:03
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
FILTER_VALIDATE_EMAIL not only doesn't support whitespace folding and comments. It only checks Addr-spec part of email address. Otherwise it should mark such address as valid: 'Test Example <test@example.com>' because it is valid according to RFC 822.

Also address "test@localhost" should be valid. Which is mentioned in another note.

You can test it with this code:
<?php

$emails 
= array(
   
'Test Example <test@example.com>',
   
'test@localhost',
   
'test@localhost.com'
);

foreach (
$emails as $email) {
    echo (
filter_var($emailFILTER_VALIDATE_EMAIL)) ? 
       
"[+] Email '$email' is valid\n" 
       
"[-] Email '$email' is NOT valid\n";
}
?>

Output for PHP 5.3.21 - 7.0.1 :
[-] Email 'Test Example <test@example.com>' is NOT valid
[-] Email 'test@localhost' is NOT valid
[+] Email 'test@localhost.com' is valid
2016-01-05 14:48:26
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
FILTER_VALIDATE_INT first casts its value to string which produces unexpected result for bool and float (https://bugs.php.net/bug.php?id=72490):

<?php

// Prints int(1).
var_dump(filter_var(trueFILTER_VALIDATE_INT));

// ...but this prints bool(false).
var_dump(filter_var(falseFILTER_VALIDATE_INT));

// --------

// Prints bool(false).
var_dump(filter_var(1.1FILTER_VALIDATE_INT));

// ...but this prints int(0).
var_dump(filter_var(0.0FILTER_VALIDATE_INT));

// ...but this again is bool(false).
var_dump(filter_var('0.0'FILTER_VALIDATE_INT));

// Also bool(false).
var_dump(filter_var('-0.0'FILTER_VALIDATE_INT));

?>

Live sample: https://3v4l.org/CZW0W

The docs are not clear on how exactly this casting affects the result for certain input values.
2016-06-30 11:18:02
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
A word to the wise regarding floats.

$t = '312041.25 &euro; instead of 896.70 &euro;';
echo filter_var ($t, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

will return
312041.25896.70
which is likely not what you were expecting. In 2007 someone suggested it's not acceptable (see https://bugs.php.net/bug.php?id=40156&edit=2) but it was flagged "not a bug" because these kind of filters are only supposed to filter out illegal characters.
Of course if you were to use FILTER_VALIDATE_FLOAT it would just return that the input is not valid.
2017-05-04 17:47:02
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
FILTER_FLAG_QUERY_REQUIRED is failing URLs that are encoded e.g.

http://example.com/page.php?q=growing+big

Fails whilst

http://example.com/page.php?q=big

So anything more than one word encoded fails.

Tested on PHP version 7.1
2018-01-30 20:36:33
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
`FILTER_FLAG_EMAIL_UNICODE` was added in PHP 7.1
2019-08-12 13:09:32
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Автор:
since php 7.4 
you can use these 3 beautiful conditions for from validation for validation less, great or in range

<?php
/**
 * less_than_equal_to
 */
$x 50;
if (
filter_var($xFILTER_VALIDATE_FLOAT, ["options" => ["max_range" => 100]]) !== false) {
    echo 
"result : $x is less than OR equal to 100";
} else {
    echo 
"result : $x is NOT less than OR equal to 100";
}
?>
result : 50 is less than OR equal to 100

<?php
/**
 * greater_than_equal_to 
 */
$x 50;
if (
filter_var($xFILTER_VALIDATE_FLOAT, ["options" => ["min_range" => 100]]) !== false) {
    echo 
"result : $x is greater than OR equal to 100";
} else {
    echo 
"result : $x is NOT greater than OR equal to 100";
}
?>
result : 50 is NOT greater than OR equal to 100

<?php
/**
 * less_than_equal_to && greater_than_equal_to
 */
$x 50;
if (
filter_var($xFILTER_VALIDATE_FLOAT, ["options" => ["min_range" => "max_range"=> 100]]) !== false) {
    echo 
"result : $x is in range of 0 to 100";
} else {
    echo 
"result : $x in NOT range of 0 to 100";
}
?>
result : 50 is in range of 0 to 100
2020-04-03 01:17:52
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Looks like FILTER_VALIDATE_DOMAIN isn't available on PHP < 7:

https://3v4l.org/eOPLM
2020-05-05 22:47:22
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Please note that the FILTER_FLAG_NO_PRIV_RANGE flag does not exclude IPv4 private addresses in the IPv6 namespace, such as ::ffff:169.254.169.254.
2020-05-13 20:20:26
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
Note that some flags are removed in PHP 8. E.g. FILTER_FLAG_HOST_REQUIRED
2021-11-11 11:42:22
http://php5.kiev.ua/manual/ru/filter.filters.validate.html
FILTER_VALIDATE_FLOAT Security Risk CVE-2021-21708 High Risk from 

Warning from MITRE Corporation, Common Vulnerabilities and Exposures:

In PHP versions 7.4.x below 7.4.28, 8.0.x below 8.0.16, and 8.1.x below 8.1.3, when using filter functions with FILTER_VALIDATE_FLOAT filter and min/max limits, if the filter fails, there is a possibility to trigger use of allocated memory after free, which can result it crashes, and potentially in overwrite of other memory chunks and RCE. This issue affects: code that uses FILTER_VALIDATE_FLOAT with min/max limits.

(Source: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-21708)
2022-03-07 10:12:31
http://php5.kiev.ua/manual/ru/filter.filters.validate.html

    Поддержать сайт на родительском проекте КГБ