admin管理员组文章数量:1122846
I would like to sanitize an input field of type integer WordPress. Like this..
<input type="number" name="amount" />
Now, what should I do?
I would like to sanitize an input field of type integer WordPress. Like this..
<input type="number" name="amount" />
Now, what should I do?
Share Improve this question asked Aug 18, 2021 at 9:02 Tarikul IslamTarikul Islam 215 bronze badges 4 |1 Answer
Reset to default 0It is odd that WordPress still does not provide a function to sanitize numbers. A common issue is that (int)
, etc. simply truncate the input and fail if the input contains separators. Forcing a type on input like 4,000
produces 4
not 4000
, and separators are different depending on the locale.
There is NumberFormatter::parse()
, which is quite strict:
$nf = new NumberFormatter('en_CA', NumberFormatter::DECIMAL);
var_dump($nf->parse('4 500,9', NumberFormatter::TYPE_INT64));
var_dump($nf->parse('4 5002,9', NumberFormatter::TYPE_INT64));
Output:
int(4500)
bool(false)
It also truncates numbers, and fails if input is not exactly the right format.
Alternatively, input can be parsed assuming anything that isn't an Arabic numeral (0-9), or the locale's decimal point, is irrelevant:
# get the expected decimal point character for the current locale
$radix = nl_langinfo(DECIMAL_POINT);
# fall back to "." if locale function failed, and escape it for use in PCRE
$radix = preg_quote($radix === false ? '.' : $radix, '/');
# scrub out anything that's not a digit or the decimal point
$parsed = preg_replace("/[^\d$radix]+/", '', $input);
# get number parts and tolerate repeated decimal points
$parsed = preg_split("/$radix+/", $parsed);
# either truncate any fraction...
$parsed_truncated = (int) $parsed[0];
# or round it
$parsed_rounded = (int) round($parsed[0] . '.' . ($parsed[1] ?? '0'), 0);
The rounded output will be 1010
from input like 10,0 9. 7
. It doesn't handle negative numbers, but they could be detected by first searching the input for the presence of the character returned by nl_langinfo(NEGATIVE_SIGN)
.
本文标签: phpHow to sanitize any integer input field in wordpress
版权声明:本文标题:php - How to sanitize any integer input field in wordpress? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736287605a1927917.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
absint()
, but for other types of numbers would would use core PHP functions. A price probably also requires a certain number of decimal places an potentially other things, so you would need to write your own function. So either way, this would be unrelated to WordPres. – Jacob Peattie Commented Aug 18, 2021 at 10:03