PHP.mk документација

filter_var

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.filter-var.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.filter-var.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
filter_var

Референца за `function.filter-var.php` со подобрена типографија и навигација.

function.filter-var.php

filter_var

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

filter_varФилтрира променлива со одреден филтер

= NULL

filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed

Филтрирај променлива користејќи FILTER_VALIDATE_* филтри за валидација, FILTER_SANITIZE_* филтри за чистење, или прилагоден филтер.

Параметри

value
Вредност за филтрирање.
Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Скаларни вредности се претворени во стринг внатрешно пред да бидат филтрирани.

filter
Филтер што треба да се примени. Може да биде филтер за валидација со користење на еден од FILTER_VALIDATE_* константите, филтер за чистење со користење на еден од FILTER_SANITIZE_* or FILTER_UNSAFE_RAW, или прилагоден филтер со користење на FILTER_CALLBACK.

Забелешка: Стандардно е FILTER_DEFAULT, што е алијас на FILTER_UNSAFE_RAW. Ова ќе резултира со никакво филтрирање по стандард.

options
Асоцијативна array на опции, или битно поле од константите на знамињата на филтерот FILTER_FLAG_*. Ако filter прифаќа опции, знамињата може да се обезбедат со користење на "flags" поле од низата.

Вратени вредности

При успех враќа филтрирани податоци. При неуспех false се враќа, освен ако FILTER_NULL_ON_FAILURE се користи знамето, во кој случај null се враќа.

Примери

ако е овозможен колекторот за отпадоци, filter_var() example

<?php
var_dump
(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('https://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

string(15) "[email protected]"
bool(false)

Пример #2 Пример за валидирање на внесувања во низа

<?php
$emails
= [
"[email protected]",
"[email protected]",
"invalidemail"
];

var_dump(filter_var($emails, FILTER_VALIDATE_EMAIL, FILTER_REQUIRE_ARRAY));
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

array(3) {
  [0]=>
  string(15) "[email protected]"
  [1]=>
  string(18) "[email protected]"
  [2]=>
  bool(false)
}

Пример #3 Пример за поминување на низа за options

<?php

$options
= [
'options' => [
'min_range' => 10,
],
'flags' => FILTER_FLAG_ALLOW_OCTAL,
];

var_dump(filter_var('0755', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('011', FILTER_VALIDATE_INT, $options));

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

int(493)
bool(false)

Пример #4 Обезбедување знамиња или директно или преку array

<?php

$str
= 'string';

var_dump(filter_var($str, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
var_dump(filter_var($str, FILTER_VALIDATE_BOOLEAN, ['flags' => FILTER_NULL_ON_FAILURE]));

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

NULL
NULL

Види Исто така

  • filter_var_array() - Добива повеќе променливи и опционално ги филтрира
  • filter_input() - Добива специфична надворешна променлива по име и опционално ја филтрира
  • filter_input_array() - Добива надворешни променливи и опционално ги филтрира
  • Филтри за валидација FILTER_VALIDATE_*
  • Филтри за чистење FILTER_SANITIZE_*

Белешки од корисници 30 белешки

cabrinosimone на gmail точка com
12 години пред
Pay attention that the function will not validate "not latin" domains.

if (filter_var('уникум@из.рф', FILTER_VALIDATE_EMAIL)) { 
    echo 'VALID'; 
} else {
    echo 'NOT VALID';
}
gt на kani точка hu
12 години пред
I found some addresses that FILTER_VALIDATE_EMAIL rejects, but RFC5321 permits:
<?php
foreach (array(
        '[email protected]',
        '(comment)[email protected]',
        '"this is v@lid!"@example.com', 
        '"much.more unusual"@example.com',
        'postbox@com',
        'admin@mailserver1',
        '"()<>[]:,;@\\"\\\\!#$%&\'*+-/=?^_`{}| ~.a"@example.org',
        '" "@example.org',
    ) as $address) {
    echo "<p>$address is <b>".(filter_var($address, FILTER_VALIDATE_EMAIL) ? '' : 'not')." valid</b></p>";
}
?>
Results:

[email protected] is not valid
(comment)[email protected] is not valid
"this is v@lid!"@example.com is not valid
"much.more unusual"@example.com is not valid
postbox@com is not valid
admin@mailserver1 is not valid
"()<>[]:,;@\"\\!#$%&'*+-/=?^_`{}| ~.a"@example.org is not valid
" "@example.org is not valid

The documentation does not saying that FILTER_VALIDATE_EMAIL should pass the RFC5321, however you can meet with these examples (especially with the first one). So this is a note, not a bug report.
Случаен тип
пред 2 години
Actually, this is not really a helpful comment for a manual (so, don't upvote), but as search engines don't find a lot of occurrences for the error message and especially no helpful hint, it might save somebody some time.

If you're getting an error message like "filter_var(): Unknown filter with ID 2097152" or a different number, you just accidentally mixed up the parameters. So, instead of

<?php
filter_var($ip, FILTER_FLAG_IPV6)
?>

you should try it with

<?php
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)
?>

and it will work ;) I know, this isn't the most intuitive form you can design a function and it's tempting to throw everything into one param as it is done for regular checks, but, yeah, it is how it is.
[email protected]
пред 8 години
note that FILTER_VALIDATE_BOOLEAN tries to be smart, recognizing words like Yes, No, Off, On, both string and native types of true and false, and is not case-sensitive when validating strings.

<?php
$vals=array('on','On','ON','off','Off','OFF','yes','Yes','YES',
'no','No','NO',0,1,'0','1','true',
'True','TRUE','false','False','FALSE',true,false,'foo','bar');
foreach($vals as $val){
    echo var_export($val,true).': ';   var_dump(filter_var($val,FILTER_VALIDATE_BOOLEAN,FILTER_NULL_ON_FAILURE));
}
?>

outputs:
'on': bool(true)
'On': bool(true)
'ON': bool(true)
'off': bool(false)
'Off': bool(false)
'OFF': bool(false)
'yes': bool(true)
'Yes': bool(true)
'YES': bool(true)
'no': bool(false)
'No': bool(false)
'NO': bool(false)
0: bool(false)
1: bool(true)
'0': bool(false)
'1': bool(true)
'true': bool(true)
'True': bool(true)
'TRUE': bool(true)
'false': bool(false)
'False': bool(false)
'FALSE': bool(false)
true: bool(true)
false: bool(false)
'foo': NULL
'bar': NULL
remindfwd
пред 2 години
Please note that the following will return true, even if the URL is not correct. Because it validates only the domain, subdomain, path and query, not the protocol.

<?php
filter_var( 'http://https://example.com', FILTER_VALIDATE_URL );
?>

Please read more on https://www.php.net/manual/en/filter.filters.validate.php
Анди, info на pragmamx точка org
пред 13 години
And this is also a valid url 

http://example.com/"><script>alert(document.cookie)</script>
Стив
пред 7 години
The note from "hek" about HTML5 having patterns thus alleviating the need to filter in PHP is completely wrong:  You still must filter input on the server side.  The HTML5 form inputs are client-side, meaning they are completely under the user's control.  Only when you receive the data in PHP is it server-side and under your control.  Once the data is under your control, then you must filter/sanitize it properly.

This is true regardless of server-side language.  I would encourage the moderators to remove the note from "hek" because it will mislead people with horrible consequences.

Steve
Анонимен
пред 10 години
FILTER_VALIDATE_URL allows:

filter_var('javascript://comment%0Aalert(1)', FILTER_VALIDATE_URL);

Where the %0A (URL encoded newline), in certain contexts, will split the comment from the JS code.

This can result in an XSS vulnerability.
mpyw628 на gmail точка com
пред 7 години
I wrote a JavaScript email validator fully compatible with PHP's filter_var() implementation.

mpyw/FILTER_VALIDATE_EMAIL.js: Email validation compatible with PHP's filter_var($value, FILTER_VALIDATE_EMAIL) 
https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js
dale точка liszka на gmail точка com
пред 17 години
Using the FILTER_CALLBACK requires an array to be passed as the options:

<?php
function toDash($x){
   return str_replace("_","-",$x);
} 

echo filter_var("asdf_123",FILTER_CALLBACK,array("options"=>"toDash"));
// returns 'asdf-123'
?>
crisp на tweakers точка net
пред 8 години
Note that only using FILTER_VALIDATE_URL to validate url's input may result in XSS:

$url = 'javascript://%0Aalert(document.cookie)';

if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)) {
    echo '<a href="' . $url . '">click</a>';
}

You should at least additionally check the actually used scheme.
Гај Сарторели
пред 2 години
Note that filter_var() with FILTER_VALIDATE_URL uses RFC2396 which is obsolete. This means it treats some currently valid characters (such as "_") as being invalid.

In many cases it may be more beneficial to use php parse_url() which uses RFC3986 which is what is currently in effect.
clcollie на mindspring точка com
пред 13 години
It's very likely that you actually want to detect all reserved ranges, not just private IPs, and there's another constant for them that should be bitwise-OR'd with it.
<?php
function is_private_ip($ip) {
    return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
?>
dale точка liszka на gmail точка com
пред 17 години
Here is how to use multiple flags (for those who learn better by example, like me):

<?php
echo "|asdf".chr(9).chr(128)."_123|";
echo "\n";
// "bitwise conjunction" means logic OR / bitwise |
echo filter_var("|asdf".chr(9).chr(128)."_123\n|" ,FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

/*
Results:
|asdf    �_123|
|asdf_123|
*/
?>
keevitaja на gmail точка com
пред 14 години
please note FILTER_VALIDATE_URL passes following url

http://example.ee/sdsf"f
jon точка bertsch на ucop точка edu
пред 17 години
Here's an actual example of the filter syntax with a flag since there doesn't appear to be a one liner for this anywhere:

'hours' => array('filter'=>FILTER_SANITIZE_NUMBER_FLOAT, 'flags' => FILTER_FLAG_ALLOW_FRACTION, 'options'=> '.')
Роберт Влах
пред 5 години
I won't recommend using this function to validate email addresses on a normal website. The problem is that in accordance with RFC 3696 (Application Techniques for Checking and Transformation of Names) the following email addresses would be considered as valid:

customer/[email protected]
[email protected]
!def!xyz%[email protected]
[email protected]
"Abc@def"@example.com

Hardly something I would accept in a live web app in 2020 :-/
ajcorrea на gmail точка ком
пред 2 години
You can use multiple FLAGS to validate an ip address:

//Validade if input is an IPv4 Address:
$_FILTERS = array('flags' => FILTER_FLAG_IPV4);

//Validade if input is an IPv4 address and isn´t a private IP.
$_FILTERS = array('flags' => FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE);

//Validade if input is an IPv4 and isn´t a reserved IP.
$_FILTERS = array('flags' => FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE);

//Validade if input is an IPv4, isn´t a private IP and isn´t a reserved IP.
$_FILTERS = array('flags' => FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);

filter_var($_input, FILTER_VALIDATE_IP, $_FILTERS);
axew3 на me точка you
пред 1 година
I've see some report about FILTER_VALIDATE_URL and i also would like to  add mine, because into a stupid code like this:
<?php
$ckOrigin = 'https://forum.myw3host.comhttps://forum.myw3host.comhttps://forum.myw3host.com/viewtopic.php?p=45#p45';

if(filter_var($ckOrigin, FILTER_VALIDATE_URL)){
    echo 'ok the URL is valid';
}
?>

since i was sure that in case the url were wrong it had returned false, I spent a lot of time to realize that it instead fail into a string like the one above, and it return true.
Анонимен
3 години пред
Pay attention:
questionmark in url is also valid

<?php
echo filter_var("http://test???test.com", FILTER_VALIDATE_URL)?"valid":"not valid"; #valid
?>
dakaenev на gmail точка ком
пред 2 години
As reply of https://www.php.net/manual/en/function.filter-var.php#128235

if you use FILTER_FLAG_PATH_REQUIRED it work correct.

var_dump( filter_var('http://test???test.com/path/?t=1', FILTER_VALIDATE_URL)  ); // true

var_dump( filter_var('http://test???test.com/path/?t=1', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)  ); // false
joe на bloe точка ком
пред 11 години
"(comment)[email protected]"
is an invalid E-Mail address per RFC5322 (Appendix A.6.3):
"Also, the comments and white space throughout addresses, dates, and message identifiers are all part of the obsolete syntax."
interghost at crovortex dot com
пред 17 години
Note that when using FILTER_VALIDATE_INT along with the FILTER_FLAG_ALLOW_HEX flag, the string "2f", for example, is not validated successfully, because you must use the "0x" prefix, otherwise, it treats the data as base 10.

The range options are also smart enough to recognize when the boundaries are exceeded in different bases.

Here's an example:

<?php

$foo = '256';
$bar = '0x100';
var_dump(validate_int($foo)); // false, too large
var_dump(validate_int($bar)); // false, too large

function validate_int($input)
{
  return filter_var(
    $input,
    FILTER_VALIDATE_INT,

    // We must pass an associative array
    // to include the range check options.
    array(
      'flags'   => FILTER_FLAG_ALLOW_HEX,
      'options' => array('min_range' => 1, 'max_range' => 0xff)
    )
  );
}

?>
php на maisqi точка ком
пред 14 години
FILTER_VALIDATE_URL does not support internationalized domain name (IDN). Valid or not, no domain name with Unicode chars on it will pass validation.

We can circumvent this with a home grown solutions, but C code is C code, so I've gone for the code bellow, which builds on filter_var().

<?php
$res = filter_var ($uri, FILTER_VALIDATE_URL);
if ($res) return $res;
// Check if it has unicode chars.
$l = mb_strlen ($uri);
if ($l !== strlen ($uri)) {
    // Replace wide chars by “X”.
    $s = str_repeat (' ', $l);
    for ($i = 0; $i < $l; ++$i) {
        $ch = mb_substr ($uri, $i, 1);
        $s [$i] = strlen ($ch) > 1 ? 'X' : $ch;
    }
    // Re-check now.
    $res = filter_var ($s, FILTER_VALIDATE_URL);
    if ($res) {    $uri = $res; return 1;    }
}
?>

The logic is simple. A non-ascii char is more than one byte long. We replace every one of those chars by "X" and check again.

An alternative will be to punycode the URI before calling filter_var(), but PHP lacks native support for punycode. I think my approach is effective. Please e-mail me if you think otherwise or see room for improvement.
yoanlin93 на gmail точка ком
пред 10 години
Some boolean conversions:

<?php
var_dump(filter_var('oops', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// NULL

var_dump(filter_var('false', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var('true', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var(0, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var(1, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var('TRUE', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var('', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var('FALSE', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)
drew_mirage на hotmail точка ком
12 години пред
One key thing to remember about filtering integers is that the value for the option max_range must be less than or equal to the value of PHP_INT_MAX.

filter_var($someVariable, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => SOME_VALUE_GREATER_THAN_PHP_INT_MAX)));

This will fail even if $someVariable is a valid integer in the expected range.

This can show up when you are attempting to validate a potential key for an unsigned MySQL INT type (whose maximum value is 4294967295) on a 32-bit system, where the value of PHP_INT_MAX is 2147483647.
mmerlone на gmail точка ком
пред 4 години
Be aware that FILTER_FLAG_PATH_REQUIRED is happy with a single slash (/), so:

<?php
$options = array('flags' => FILTER_FLAG_PATH_REQUIRED);
filter_var('http://example.com', FILTER_VALIDATE_URL, $options); // returns false
filter_var('http://example.com/', FILTER_VALIDATE_URL, $options); // returns 'http://example.com/'
?>
buttflattery на gmail точка ком
пред 10 години
FILTER_VALIDATE_URL validates a url like http://www.
7 белешки
12 години пред
It is important to note that though the data type of the first parameter of the function is stated as "mixed", this is only one half of the truth.

While it accepts any data type, the first parameter will always be cast to string before being validated or sanitized.

It seems that this function was designed strictly to be used on user input strings. For example: from an online-form. When using it for anything other than that, you may see issues. So read the documentation very carefully!

Especially note that there is an (to date) unresolved issue (#49510) concerning the Boolean filter while using the FILTER_NULL_ON_FAILURE flag. Note that both (string) FALSE and FALSE are not recognized as boolean values and will return NULL (not FALSE as you might expect).

I thus personally suggest that (to date) the best way to take the filter_var()-functions beyond their original purpose (and allow future extension and customization) is to wrap them in your own classes. This will allow you to work-around unexpected behavior on non-string input and add your custom checks, or back-port filters or sanitizers that may be added in later versions of PHP.
(Especially since PHP currently still lacks filters and sanitizers for some of the more exotic HTML5 input types, like "color". Thus there actually is a chance that we may see a need for custom filters or backports at some point in the future.)
Анонимен
пред 7 години
Replying to Andi:

This is NOT a valid URL, as the characters are not encoded

http://example.com/"><script>alert(document.cookie)</script>

This is a valid URL:

http://example.com/%22%3E%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.