验证:似乎忽略了字母字符不是数字的事实


Validation: seems to disregard the fact that alpha characters are not numerical

根据标题,当用户在两个计算字段中的任何一个中输入恶意输入(不是1或0)时,我在二进制计算器中遇到触发错误的问题。

输入应限制为1或0。为什么当我输入"a"时,计算仍会继续?

$submit = htmlspecialchars(strip_tags(stripslashes($_POST['submit'])));
$val1 = htmlspecialchars(strip_tags(stripslashes($_POST['val1'])));
$val2 = htmlspecialchars(strip_tags(stripslashes($_POST['val2'])));
$val1_length = strlen($val1);
$val2_length = strlen($val2);
$val1 = array_reverse(str_split($val1, 1));
$val2 = array_reverse(str_split($val2, 1));
// Val 1 - Checking
$count = 0; // count variable counts how many times the loop recurs and stops it appropriately
while ($count < $val1_length) {
if(($val1[$count] != 0) && ($val1[$count] != 1) && (is_numeric($binary_input))) { // checks if input is comprised of 0 or 1
    showInputError();   
    exit(); // input does not contain 0 or 1, abort script and do not attempt further calculations
}
$count = $count + 1; // increment the count variable after one successful loop
} // Val1 was fine

由于a不是数字,因此继续。检查此行:

if(($val1[$count] != 0) && ($val1[$count] != 1) && (is_numeric($binary_input))) {

如果不等于0也不等于1,则转换为:,并且是数字a:不等于0也不等于1,数字->继续。

更改为类似

if(!is_numeric($val1[$count]) || !in_array(intval($val1[$count]),array(0,1)))

我不知道$binary_input是什么,请解释一下。

$binary_input来自哪里?我想你应该在那里检查$val1$val2,而且因为你想在输入不是数字的情况下显示错误,所以你应该检查!(is_numeric($val1) && is_numeric($val2))。。。