問題描述
我已經安裝了 PHP 8.1 并開始測試我的舊項目.我使用了過濾器 FILTER_SANITIZE_STRING
像這樣:
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);
現在我收到此錯誤:
已棄用:不推薦使用常量 FILTER_SANITIZE_STRING
Deprecated: Constant FILTER_SANITIZE_STRING is deprecated
當我使用 FILTER_SANITIZE_STRIPPED
時也會發生同樣的情況:
The same happens when I use FILTER_SANITIZE_STRIPPED
:
已棄用:不推薦使用常量 FILTER_SANITIZE_STRIPPED
Deprecated: Constant FILTER_SANITIZE_STRIPPED is deprecated
我可以用什么代替它?
推薦答案
這是一個用途可疑的過濾器.很難說它究竟要完成什么任務或何時應該使用它.由于其名稱,它也與默認字符串過濾器混淆,而實際上默認字符串過濾器稱為 FILTER_UNSAFE_RAW
.PHP 社區決定不再支持使用此過濾器.
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
. The PHP community decided that the usage of this filter should not be supported anymore.
此過濾器的行為非常不直觀.它刪除了 <
和字符串結尾之間或直到下一個 >
之間的所有內容.它還刪除了所有 NUL
字節.最后,它將 '
和 "
編碼到它們的 HTML 實體中.
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:
使用不進行任何過濾的默認字符串過濾器
FILTER_UNSAFE_RAW
.如果您對FILTER_SANITIZE_STRING
的行為一無所知,而您只想使用一個默認過濾器來為您提供字符串值,則應該使用它.
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 ofFILTER_SANITIZE_STRING
and you just want to use a default filter that will give you the string value.
如果您使用此過濾器來防御 XSS 漏洞,請將其替換為 htmlspecialchars()
.不要在輸入數據上調用此函數.為了防止 XSS,您需要對輸出進行編碼!
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!
如果您確切地知道該過濾器的作用并且想要創建一個 polyfill,則可以使用正則表達式輕松完成.
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);
}
這篇關于不推薦使用常量 FILTER_SANITIZE_STRING的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!