Add two random variables, if the answer is right, submit form

-2

On a form, there is a field where you will need to perform a math operation. If the result of this operation is right, it allows the sending, otherwise it will not. The operation should contain two random numbers from 1 to 9.

For example: 1 + 2 = 3 (send the form).

How to do this in PHP?

    
asked by anonymous 09.03.2018 / 18:25

1 answer

-2

You can validate the sum with JavaScript before sending (you will only submit the form if the sum is correct): by dvd

<?php

   $n1 = rand(1,9);
   $n2 = rand(1,9);
   $soma = $n1+$n2;        
?>

<form method="post" action="">
<br>
<label for="captcha">Não sou robot: <?php echo $n1." + ".$n2 ?> =</label>
<input type="text" name="captcha" id="captcha" />
<input type="hidden" name="soma" id="soma" value="<?php echo $soma ?>" />
<input type='submit' value='Enviar'>
</form>

<script>
var form = document.body.querySelector("form");

form.addEventListener("submit", function(e){

   var capt = document.body.querySelector("#captcha"),
       resu = document.body.querySelector("#soma");

   if(resu.value == capt.value){
      //envia o formulário
      alert("Soma OK!");
   }else{
      // não envia o formulário
      console.log("Soma incorreta");
      e.preventDefault();
   }
});
</script>
    
09.03.2018 / 22:08