Logic error in PHP when constructing if elseif Else

Asked

Viewed 396 times

2

I have a simple email form with reCaptcha.

To avoid the user sending the email and keep giving F5 and sending the same email several times, I did a redirect in a php script. But there is a logic error in this script, because although the two variables are false he is sending the same email!

Note that the structure of the script should be like this (if variable == false, elseif, Else and not if variable == true, if, if as usual), because to redirect the page I change the php header and this should be the first thing to be done before giving print commands (print, echo, html outside the script).

Here is my code, note that it prints out the two false variables and prints "all ok".

<?php

$ok_post = false;
$ok_captcha = false;

echo "ok_post = ", (int)$ok_post;
echo "<br>ok_captcha = ", (int)$ok_captcha;

if ((!ok_post && !ok_captcha) || (!ok_post && ok_captcha)) {

  echo '<br>Formulário vazio.';

} elseif (!ok_captcha && ok_post) {

  echo '<br>Captcha vazio.';

} else {

  echo '<br>Tudo ok!';

}

?>

output:

ok_post = 0
ok_captcha = 0
Tudo ok!

EDIT: The following python script works as it should, so I’ve come to the conclusion that I’m using some PHP operator wrong, but I don’t know which one.

ok_post = False
ok_captcha = False

print 'ok_post', ok_post
print 'ok_captcha', ok_captcha

if not ok_post and not ok_captcha or not ok_post and ok_captcha:
  print 'formulario vazio'
elif not ok_captcha and ok_post:
  print 'captcha vazio'
else:
  print 'ok'

output:

ok_post False
ok_captcha False
formulario vazio

1 answer

6


Your mistake was simple, you didn’t put the $ of variáveis at the time of the if and elseif .

Script correct:

<?php

$ok_post = false;
$ok_captcha = false;

echo "ok_post = ", (int)$ok_post;
echo "<br>ok_captcha = ", (int)$ok_captcha;

if ((!$ok_post && !$ok_captcha) || (!$ok_post && $ok_captcha)) {

  echo '<br>Formulário vazio.';

} elseif (!$ok_captcha && $ok_post) {

  echo '<br>Captcha vazio.';

} else {

  echo '<br>Tudo ok!';

}

?>
  • Gosh, how could I not see that? I thought I was writing in python. Hahaha. Thank you.

  • Sometimes we are so within the code that these things happen, so it’s good to share. I’ve already lost 5hours because of a , hahaha is part. Abs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.