我用谷歌搜索了这个,还在 Stackoverflow 上搜索了答案。但对于如何清理复选框值,还没有真正明确的答案。
我理解如果我的输入是:
<input type="checkbox" value="submit_doors">
有人可以在他们的开发工具中替换该值 - 并且此信息将被发送到服务器。
那么我应该如何清理复选框/ radio 输入?我是否应该使用 (int) 检查该值,是否应该像处理所有其他输入/选择字段一样清理该值?
郑重声明,我正在使用 WordPress 开发我的网站,并且为了清理文本输入,例如我正在这样做:
$turbo = trim( sanitize_text_field( wp_kses( $_POST['submit_induction_turbo'], $allowed_html ) ) );
我是否也应该对复选框运行所有这些检查?或者这是矫枉过正?
最佳答案
首先,您需要为输入字段命名,以便您可以从 $_POST 变量访问它。
假设您有以下输入字段并且您想要清理它。
<input type="checkbox" name="door" value="submit_doors">
您可以使用该函数清理任何复选框。
/**
* 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 '';
}
}
例如:如果你想检查你的用户是否提交了复选框中的值“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.
这样,功能就灵活了。如果传递给第二个参数,它可以清理真假值和 1 以及其他字符串值。
关于php - 如何清理复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42881968/