The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
-
Input Constants
-
INPUT_POST(int) -
POST variables.
-
INPUT_GET(int) -
GET variables.
-
INPUT_COOKIE(int) -
COOKIE variables.
-
INPUT_ENV(int) -
ENV variables.
-
INPUT_SERVER(int) -
SERVER variables.
-
INPUT_SESSION(int) -
SESSION variables. (Removed as of PHP 8.0.0; was not implemented previously)
-
INPUT_REQUEST(int) -
REQUEST variables. (Removed as of PHP 8.0.0; was not implemented previously)
These constants are used by filter_input() and filter_input_array().
-
Generic Filter Flags
-
FILTER_FLAG_NONE(int) -
No flags.
-
FILTER_REQUIRE_SCALAR(int) -
Flag used to require the input of the filter to be a scalar.
-
FILTER_REQUIRE_ARRAY(int) -
Flag used to require the input of the filter to be an array.
-
FILTER_FORCE_ARRAY(int) -
This flag wraps scalar inputs into a one element array for filters which operate on arrays.
-
FILTER_NULL_ON_FAILURE(int) -
Use
nullinstead offalseon failure.Usable with any validation
FILTER_VALIDATE_*filter. -
FILTER_THROW_ON_FAILURE(int) -
Throws a Filter\FilterFailedException when a validation filter fails, instead of returning
false.Can be used with any validation
FILTER_VALIDATE_*filter.Available as of PHP 8.5.0.
-
Sanitization Filter Flags
-
FILTER_FLAG_STRIP_LOW(int) -
Strip characters with ASCII value less than 32.
-
FILTER_FLAG_STRIP_HIGH(int) -
Strip characters with ASCII value greater than 127.
-
FILTER_FLAG_STRIP_BACKTICK(int) -
Strips backtick (
`) characters. -
FILTER_FLAG_ENCODE_LOW(int) -
Encode characters with ASCII value less than 32.
-
FILTER_FLAG_ENCODE_HIGH(int) -
Encode characters with ASCII value greater than 127.
-
FILTER_FLAG_ENCODE_AMP(int) -
Encode
&. -
FILTER_FLAG_NO_ENCODE_QUOTES(int) -
Single and double quotes (
'and") will not be encoded. -
FILTER_FLAG_EMPTY_STRING_NULL(int) -
If sanitizing a string results in an empty string, convert the value to
null
-
Validation Filters
-
FILTER_VALIDATE_BOOL(int) -
Returns
truefor"1",1including binary, octal and hexadecimal notations,1.0including scientific notation,"true",true,"on", and"yes".Returns
falsefor"0",0including binary, octal and hexadecimal notations,0.0including scientific notation,"false",false,"off","no", and"".String values are compared case-insensitively. The return value for non-boolean values depends on the
FILTER_NULL_ON_FAILURE. If it is set,nullis returned, otherwisefalseis returned.-
Available options
default-
Value to return in case the filter fails.
Available as of PHP 8.0.0.
-
FILTER_VALIDATE_BOOLEAN(int) -
Alias of
FILTER_VALIDATE_BOOL. The alias was available prior to the introduction of its canonical name in PHP 8.0.0. -
FILTER_VALIDATE_INT(int) -
Validates whether the value is an integer, on success it is converted to type int.
Note:
String values are trimmed using trim() before validation.
-
Available options
default-
Value to return in case the filter fails.
min_range-
Value is only valid if it is greater than or equal to the provided value.
max_range-
Value is only valid if it is less than or equal to the provided value.
-
Optional Flags
-
FILTER_FLAG_ALLOW_OCTAL(int) -
Allow integers in octal notation (
0[0-7]+). -
FILTER_FLAG_ALLOW_HEX(int) -
Allow integers in hexadecimal notation (
0x[0-9a-fA-F]+).
-
FILTER_VALIDATE_FLOAT(int) -
Validates whether the value is a float, on success it is converted to type float.
Note:
String values are trimmed using trim() before validation.
-
Available options
default-
Value to return in case the filter fails.
decimalmin_range-
Value is only valid if it is greater than or equal to the provided value. Available as of PHP 7.4.0.
max_range-
Value is only valid if it is less than or equal to the provided value. Available as of PHP 7.4.0.
-
Optional Flags
-
FILTER_FLAG_ALLOW_THOUSAND(int) -
Accept commas (
,), which usually represent the thousand separator.
-
FILTER_VALIDATE_REGEXP(int) -
Validates value against the regular expression provided by the
regexpoption.-
Available options
default-
Value to return in case the filter fails.
regexp-
Perl-compatible regular expression.
-
FILTER_VALIDATE_URL(int) -
Validates whether the URL is valid according to » RFC 2396.
-
Available options
default-
Value to return in case the filter fails.
-
Optional Flags
-
FILTER_FLAG_SCHEME_REQUIRED(int) -
Requires the URL to contain a scheme part.
Warning
DEPRECATED as of PHP 7.3.0 and REMOVED as of PHP 8.0.0. This is because it is always implied by the
FILTER_VALIDATE_URLfilter. -
FILTER_FLAG_HOST_REQUIRED(int) -
Requires the URL to contain a host part.
Warning
DEPRECATED as of PHP 7.3.0 and REMOVED as of PHP 8.0.0. This is because it is always implied by the
FILTER_VALIDATE_URLfilter. -
FILTER_FLAG_PATH_REQUIRED(int) -
Requires the URL to contain a path part.
-
FILTER_FLAG_QUERY_REQUIRED(int) -
Requires the URL to contain a query part.
Warning
A valid URL may not specify the HTTP protocol (
http://). Therefore, further validation may be required to determine if the URL uses an expected protocol, e.g.ssh://ormailto:.Warning
This filter only works on ASCII URLs. This means that Internationalized Domain Names (IDN) will always be rejected.
-
FILTER_VALIDATE_DOMAIN(int) -
Validates whether the domain name is valid according to » RFC 952, » RFC 1034, » RFC 1035, » RFC 1123, » RFC 2732, and » RFC 2181.
-
Available options
default-
Value to return in case the filter fails.
-
Optional Flags
-
FILTER_FLAG_HOSTNAME(int) -
Require hostnames to start with an alphanumeric character and contain only alphanumerics or hyphens.
-
FILTER_VALIDATE_EMAIL(int) -
Validates whether the value is a "valid" e-mail address.
The validation is performed against the
addr-specsyntax in » RFC 822. However, comments, whitespace folding, and dotless domain names are not supported, and thus will be rejected.-
Available options
default-
Value to return in case the filter fails.
-
Optional Flags
-
FILTER_FLAG_EMAIL_UNICODE(int) -
Accepts Unicode characters in the local part. Available as of PHP 7.1.0.
Warning
Email validation is complex and the only true way to confirm an email is valid and exists is to send an email to the address.
-
FILTER_VALIDATE_IP(int) -
Validates value as IP address.
-
Available options
default-
Value to return in case the filter fails.
-
Optional Flags
-
FILTER_FLAG_IPV4(int) -
Allow IPv4 address.
-
FILTER_FLAG_IPV6(int) -
Allow IPv6 address.
-
FILTER_FLAG_NO_RES_RANGE(int) -
Deny reserved addresses.
These are the ranges that are marked as
Reserved-By-Protocolin » RFC 6890.Which for IPv4 corresponds to the following ranges:
0.0.0.0/8,169.254.0.0/16,127.0.0.0/8,240.0.0.0/4.And for IPv6 corresponds to the following ranges:
::1/128,::/128,::FFFF:0:0/96,FE80::/10. -
FILTER_FLAG_NO_PRIV_RANGE(int) -
Deny private addresses.
These are IPv4 addresses which are in the following ranges:
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16.These are IPv6 addresses starting with
FDorFC. -
FILTER_FLAG_GLOBAL_RANGE(int) -
Only allow global addresses. These can be found in » RFC 6890 where the
Globalattribute isTrue. Available as of PHP 8.2.0.
-
FILTER_VALIDATE_MAC(int) -
Validates whether the value is a MAC address.
-
Available options
default-
Value to return in case the filter fails.
-
Sanitizing Filters
-
FILTER_UNSAFE_RAW(int) -
This filter does nothing.
However, it can strip or encode special characters if used together with the
FILTER_FLAG_STRIP_*andFILTER_FLAG_ENCODE_*filter sanitization flags. -
FILTER_DEFAULT(int) -
Alias of
FILTER_UNSAFE_RAW. -
FILTER_SANITIZE_STRING(int) -
This filter strips tags and HTML-encodes double and single quotes.
Optionally it can strip or encode specified characters if used together with the
FILTER_FLAG_STRIP_*andFILTER_FLAG_ENCODE_*filter sanitization flags.The behaviour of encoding quotes can be disabled by using the
FILTER_FLAG_NO_ENCODE_QUOTESfilter flag.Warning
The way this filter strips tags is not equivalent to strip_tags().
-
FILTER_SANITIZE_STRIPPED(int) -
Alias of
FILTER_SANITIZE_STRING. -
FILTER_SANITIZE_ENCODED(int) -
This filter URL-encodes a string.
Optionally it can strip or encode specified characters if used together with the
FILTER_FLAG_STRIP_*andFILTER_FLAG_ENCODE_*filter sanitization flags. -
FILTER_SANITIZE_SPECIAL_CHARS(int) -
This filter HTML-encodes
',",<,>,&and characters with an ASCII value less than 32. Unlike theFILTER_SANITIZE_FULL_SPECIAL_CHARSfilter, theFILTER_SANITIZE_SPECIAL_CHARSfilter ignores theFILTER_FLAG_NO_ENCODE_QUOTESflag.Optionally it can strip specified characters if used together with the
FILTER_FLAG_STRIP_*filter sanitization flags, and it can encode characters with ASCII value greater than 127 usingFILTER_FLAG_ENCODE_HIGH. -
FILTER_SANITIZE_FULL_SPECIAL_CHARS(int) -
This filter is equivalent to calling htmlspecialchars() with
ENT_QUOTESset.The behaviour of encoding quotes can be disabled by using the
FILTER_FLAG_NO_ENCODE_QUOTESfilter flag.Warning
Like htmlspecialchars(), this filter is aware of the default_charset INI setting. If a sequence of bytes is detected that makes up an invalid character in the current character set then the entire string is rejected resulting in an empty string being returned.
-
FILTER_SANITIZE_EMAIL(int) -
Sanitize the string by removing all characters except latin letters (
[a-zA-Z]), digits ([0-9]), and the special characters!#$%&'*+-=?^_`{|}~@.[]. -
FILTER_SANITIZE_URL(int) -
Sanitize the string by removing all characters except latin letters (
[a-zA-Z]), digits ([0-9]), and the special characters$-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=. -
FILTER_SANITIZE_NUMBER_INT(int) -
Sanitize the string by removing all characters except digits (
[0-9]), plus sign (+), and minus sign (-). -
FILTER_SANITIZE_NUMBER_FLOAT(int) -
Sanitize the string by removing all characters except digits (
[0-9]), plus sign (+), and minus sign (-).-
Optional Flags
-
FILTER_FLAG_ALLOW_FRACTION(int) -
Accept dot (
.) character, which usually represents the separator between the integer and fractional parts. -
FILTER_FLAG_ALLOW_THOUSAND(int) -
Accept commas (
,) character, which usually represents the thousand separator. -
FILTER_FLAG_ALLOW_SCIENTIFIC(int) -
Accept numbers in scientific notation by allowing the
eandEcharacters.
Warning
If the
FILTER_FLAG_ALLOW_FRACTIONflag is not used, then the decimal separator is removed, altering the value received.<?php $number = '12.34'; var_dump(filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT)); var_dump(filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)); ?>The above example will output:
string(4) "1234" string(5) "12.34"
-
-
FILTER_SANITIZE_ADD_SLASHES(int) -
Apply addslashes() to the input. Available as of PHP 7.3.0.
-
FILTER_SANITIZE_MAGIC_QUOTES(int) -
Alias of
FILTER_SANITIZE_ADD_SLASHES.Warning
DEPRECATED as of PHP 7.3.0 and REMOVED as of PHP 8.0.0.
-
User Defined Filter
-
FILTER_CALLBACK(int) -
This filter delegates the filtering to a user defined function. The callable is passed via the
optionsparameter as the value associated to the'options'key.The callback should have the following signature:
value-
The value that is being filtered.
Note:
The value returned by the callback will be the value returned by the invoked filter function.
Example #1 Example of using
FILTER_CALLBACKto validate a login name<?php function validate_login(string $value): ?string { if (strlen($value) >= 5 && ctype_alnum($value)) { return $value; } return null; } $login = "val1dL0gin"; $filtered_login = filter_var($login, FILTER_CALLBACK, ['options' => 'validate_login']); var_dump($filtered_login); $login = "f&ke login"; $filtered_login = filter_var($login, FILTER_CALLBACK, ['options' => 'validate_login']); var_dump($filtered_login); ?>The above example will output:
string(10) "val1dL0gin" NULL
Note:
As of PHP 8.1.25 and 8.2.12, the structural flags
FILTER_REQUIRE_ARRAY,FILTER_FORCE_ARRAYandFILTER_REQUIRE_SCALARapply to this filter, andFILTER_NULL_ON_FAILUREchanges how such a structural failure is reported. In earlier versions all flags were ignored. Filter specific flags are always ignored, and since the return value of the callback is the result, the callback itself cannot fail: no flag turns afalsereturned by the callback intonullor an exception.
13
shaman_master at list dot ru ¶
6 years ago
Note: FILTER_NULL_ON_FAILURE, FILTER_REQUIRE_SCALAR, FILTER_REQUIRE_ARRAY and FILTER_FORCE_ARRAY dont have prefix "FILTER_FLAG_" but they are FLAGS!1
6 months ago
<?php
+ // Handle FILTER_FLAG_STRIP_BACKTICK
+ // Fixes bug PHP_VERSION < 5.5.24
+ if ($flags & FILTER_FLAG_STRIP_BACKTICK) {
+ $output = str_replace('`', '', $output);
+ }
?>
Revised version:
<?php
function filter_sanitize_string(mixed $value, int $flags = 0): string|false|null {
if ($flags & FILTER_FLAG_EMPTY_STRING_NULL && $value === "") {
return null;
}
if (!(is_scalar($value) || is_null($value))) {
return false;
}
// Strip HTML tags and remove NUL bytes
$value = (string)$value;
$value = strip_tags($value);
$value = str_replace("\0", "", $value);
// High/Low ASCII handling (Byte-by-byte to match legacy behavior)
$output = "";
for ($i = 0, $n = strlen($value); $i < $n; $i++) {
$char = $value[$i];
$ord = ord($char);
if ($ord < 32) {
if ($flags & FILTER_FLAG_STRIP_LOW) continue;
if ($flags & FILTER_FLAG_ENCODE_LOW) {
$output .= "&#$ord;"; // Legacy decimal encoding
continue;
}
}
if ($ord > 127) {
if ($flags & FILTER_FLAG_STRIP_HIGH) continue;
if ($flags & FILTER_FLAG_ENCODE_HIGH) {
$output .= "&#$ord;"; // This turns © into © (©)
continue;
}
}
$output .= $char;
}
// Strip backticks
// Fixes bug PHP_VERSION < 5.5.24
if ($flags & FILTER_FLAG_STRIP_BACKTICK) {
$output = str_replace('`', '', $output);
}
// Legacy ONLY encoded ampersands if FILTER_FLAG_ENCODE_AMP was set
if ($flags & FILTER_FLAG_ENCODE_AMP) {
$output = str_replace('&', '&', $output);
}
// Replicate legacy quote encoding exactly (' and ")
if (!($flags & FILTER_FLAG_NO_ENCODE_QUOTES)) {
$output = str_replace(["'", '"'], [''', '"'], $output);
}
return $output;
}1
6 months ago
We can add FILTER_FLAG_EMPTY_STRING_NULL:
<?php
- function filter_sanitize_string(mixed $value, int $flags = 0): string|false {
+ function filter_sanitize_string(mixed $value, int $flags = 0): string|false|null {
+ if ($flags & FILTER_FLAG_EMPTY_STRING_NULL && $value === "") {
+ return null;
+ }
?>
For FILTER_FLAG_STRIP_BACKTICK, there is a bug history
(https://bugs.php.net/bug.php?id=69202)
so I did not attempt to code compatility through version history.1
6 months ago
We're all looking for a polyfill to replace the FILTER_SANITIZE_STRING flag, deprecated as of PHP 8.1.0,
that behaves exactly the same for scalar and non-scalar values.
(Using htmlspecialchars() and strip_tags() are not returning exactly the same output.)
<?php
function filter_sanitize_string(mixed $value, int $flags = 0): string|false {
if (!(is_scalar($value) || is_null($value))) {
return false;
}
// Strip HTML tags and remove NUL bytes
$value = (string)$value;
$value = strip_tags($value);
$value = str_replace("\0", "", $value);
// High/Low ASCII handling (Byte-by-byte to match legacy behavior)
$output = "";
for ($i = 0, $n = strlen($value); $i < $n; $i++) {
$char = $value[$i];
$ord = ord($char);
if ($ord < 32) {
if ($flags & FILTER_FLAG_STRIP_LOW) continue;
if ($flags & FILTER_FLAG_ENCODE_LOW) {
$output .= "&#$ord;"; // Legacy decimal encoding
continue;
}
}
if ($ord > 127) {
if ($flags & FILTER_FLAG_STRIP_HIGH) continue;
if ($flags & FILTER_FLAG_ENCODE_HIGH) {
$output .= "&#$ord;"; // This turns © into © (©)
continue;
}
}
$output .= $char;
}
// Legacy ONLY encoded & if FILTER_FLAG_ENCODE_AMP was set.
if ($flags & FILTER_FLAG_ENCODE_AMP) {
$output = str_replace('&', '&', $output);
}
// Replicate legacy quote encoding exactly (' and ")
if (!($flags & FILTER_FLAG_NO_ENCODE_QUOTES)) {
$output = str_replace(["'", '"'], [''', '"'], $output);
}
return $output;
}
// Tests
$string = "It's a \"test\" \x02 <script> > & ©";
// Deprecated example:
$sanitized = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_ENCODE_HIGH);
var_dump($sanitized);
// Polyfill example:
$sanitized = filter_sanitize_string($string, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_ENCODE_HIGH);
var_dump($sanitized);
// Polyfill in filter_var() callback:
$sanitized = filter_var($string, FILTER_CALLBACK, [
'options' => function($value) {
return filter_sanitize_string($value, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_ENCODE_HIGH);
}
]);
var_dump($sanitized);
?>
Output:
string(44) "It's a "test" > & ©"
string(44) "It's a "test" > & ©"
string(44) "It's a "test" > & ©"