Good afternoon, good people of SO!
I'm trying to make a binary calculator, which adds two binary strings together and returns the result in binary.
However, my loop (used for checking the input consists of 0 or 1) seems to falter and return either a 503 (Service Temporarily Unavilable) or suggests I've hit the maximum execution time (30 secs).
I can't figure out why. It seems to bypass this problem if I change &&
to ||
, however this returns a false positive for a bad input.
Here is the code:
// 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
Thanks in advance! :)
As bwoebi said in the comments, put the bracket one line higher in the if statement, as you're not actually counting up, so the loop will go on forever if no value is found..
$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
Why don't you simply use a simple regex like
$input= '1101010001010101110101';
preg_match('/^[01]+$/', $input);
It seems to me you are not verifying your $val1_length in the while loop. What happens if your POST values are empty? You will get an infinite loop, so you might want to replace the while like this:
while ($count <= $val1_length && !empty($val1_length) {...}