Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

php - Constant FILTER_SANITIZE_STRING is deprecated

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This was a filter of dubious purpose. It's difficult to say what it was meant to accomplish exactly 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. 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:

  1. 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.

  2. 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!

  3. 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(["'", '"'], ['&#39;', '&#34;'], $str);
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...