[英]How to sanitize checkboxes?
I have googled this, and also searched for an answer here on Stackoverflow. 我已经用谷歌搜索过,并且还在Stackoverflow上搜索了答案。 But nothing has really been a clear answer on how to sanitize a checkbox value. 但是,关于如何清除复选框值,还没有一个明确的答案。
I understand that if my input is: 我了解如果我的输入是:
<input type="checkbox" value="submit_doors">
That someone can replace the value within their dev tools - and this information would be sent to the server. 有人可以替换其开发工具中的值-并将此信息发送到服务器。
So how should I go about sanitizing checkbox/radio inputs? 那么我应该如何清理复选框/无线电输入呢? Should I be checking the value with (int), should I be sanitizing the value like I do with every other input/select field? 是否应该使用(int)检查值,是否应该像处理其他所有输入/选择字段一样对值进行消毒?
For the record, I'm developing my site using WordPress, and to sanitize a text input for example I am doing this: 作为记录,我正在使用WordPress开发我的网站,并清理文本输入,例如,我正在这样做:
$turbo = trim( sanitize_text_field( wp_kses( $_POST['submit_induction_turbo'], $allowed_html ) ) );
Should I be running all these checks over checkboxes too? 我是否也应该通过复选框运行所有这些检查? Or is this overkill? 还是这太过分了?
At first you need to give your input field a name so that you can access it from $_POST variable. 首先,您需要给输入字段起一个名称,以便可以从$ _POST变量访问它。
Let's say you have the following input field and you want to sanitize it. 假设您具有以下输入字段,并且想要对其进行清理。
<input type="checkbox" name="door" value="submit_doors">
you can use the function to sanitize any checkbox. 您可以使用该功能清除所有复选框。
/**
* Sanitize checkbox
* @param int | string $input the input value to be sanitized
* @param int | string $expected_value The expected value
* @return int | string it returns the sanitize value of the checkbox.
*/
function prefix_sanitize_checkbox( $input, $expected_value=1 ) {
if ( $expected_value == $input ) {
return $expected_value;
} else {
return '';
}
}
For example: if you want to check if your user submit the value "submit_doors" from the check box, then you can use the function like this. 例如:如果您要检查用户是否从复选框中提交了“ submit_doors”值,则可以使用类似的功能。
$sanitized_value = !empty($_POST['door']) ? prefix_sanitize_checkbox($_POST['door'], 'submit_doors') : ''; // this will return the value only if the checkbox contains the value "submit_doors", otherwise, it will return empty string.
This way, the function is flexible. 这样,功能就很灵活。 It can sanitize true false value and 1 and also other string value if passed to the second argument. 如果传递给第二个参数,它可以清除true false值和1以及其他字符串值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.