I have installed PHP 8.1 and I started testing my old project. I have used the filter FILTER_SANITIZE_STRING
like so:
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
Now I get this error:
Deprecated: Constant FILTER_SANITIZE_STRING is deprecated
The same happens when I use FILTER_SANITIZE_STRIPPED
:
Deprecated: Constant FILTER_SANITIZE_STRIPPED is deprecated
What can I replace it with?
This filter had an unclear purpose. It's difficult to say what exactly it was meant to accomplish or when it should be used. It was also confused with the default string filter, due to its name, when in reality the default string filter is called FILTER_UNSAFE_RAW
. The PHP community decided that the usage of this filter should not be supported anymore.
The behaviour of this filter was very unintuitive. It removed everything between <
and the end of the string or until the next >
. It also removed all NUL
bytes. Finally, it encoded '
and "
into their HTML entities.
If you want to replace it, you have a couple of options:
Use the default string filter FILTER_UNSAFE_RAW
that doesn't do any filtering. This should be used if you had no idea about the behaviour of FILTER_SANITIZE_STRING
and you just want to use a default filter that will give you the string value.
If you used this filter to protect against XSS vulnerabilities, then replace its usage with htmlspecialchars()
. Don't call this function on the input data. To protect against XSS you need to encode the output!
If you knew exactly what that filter does and you want to create a polyfill, you can do that easily with regex.
function filter_string_polyfill(string $string): string
{
$str = preg_replace('/\x00|<[^>]*>?/', '', $string);
return str_replace(["'", '"'], [''', '"'], $str);
}
Don’t try to sanitize input. Escape output.
The closest constant you can use instead, if you intend to convert your variable in a safe html string, is FILTER_SANITIZE_FULL_SPECIAL_CHARS
From documentation you should replace it with htmlspecialchars()
.
FILTER_SANITIZE_STRING
Strip tags and HTML-encode double and single quotes, optionally strip or encode special characters. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ENCODE_QUOTES. (Deprecated as of PHP 8.1.0, use htmlspecialchars() instead.)
FILTER_SANITIZE_STRIPPED
Alias of "string" filter. (Deprecated as of PHP 8.1.0, use htmlspecialchars() instead.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With