我的while循环达到了最大执行时间,没有给出具体的、有意义的错误


My while loop hits the maximum execution time with no specific, meaningful errors given

大家下午好
我正在尝试制作一个二进制计算器,它将两个二进制字符串相加,并以二进制形式返回结果。

然而,我的循环(用于检查输入是否由0或1组成)似乎出现了问题,并返回503(服务暂时不可访问)或表明我已经达到了最大执行时间(30秒)。

我不明白为什么。如果我将&&更改为||,似乎可以绕过这个问题,但是这会为错误的输入返回假阳性。

这是代码:

// Spring cleaning - add some variables
$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($val1);
$val1 = str_split($val1, 1);
$val2 = 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)) { // 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

提前感谢!:)

正如bwoebi在评论中所说,在if语句中把括号高出一行,因为你实际上并没有在计数,所以如果没有找到值,循环将永远继续。。

$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)) { // 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

为什么不简单地使用像这样的简单正则表达式

$input= '1101010001010101110101';
preg_match('/^[01]+$/', $input);

在我看来,您没有在while循环中验证$val1_length。如果POST值为空,会发生什么?你会得到一个无限循环,所以你可能想像这样替换while:

while ($count <= $val1_length && !empty($val1_length) {...}