Reputation: 83
I'm new to coding so it's probably a stupid mistake but I just can't figur out what is going wrong. I made an email form with a function to check if it's a human sending the message. They have to answer a simple math question generated with random numbers. But when I try to check if the input is correct, something goes wrong.
The relevant parts of the code I'm using: First I generate two random numbers, calculate the correct outcome and turn the answer into a variable:
$number = array( mt_rand(1,5), mt_rand(6,10) );
$outcome = $number[1] - $number[0];
$human = $_POST['message_human'];
The part where to put the answer:
<label for="message_human">
<input type="text" style="width: 44px;" placeholder="…" name="message_human"> + <?php echo $number[0];?> = <?php echo $number[1];?>
</label>
The part to check if the answer is correct, and perform action:
if(!$human == 0){
if($human != $outcome) my_contact_form_generate_response("error", $not_human); //not human!
else { //validate presence of name and message
if(empty($message)){
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$message = "http://url.com" . $url . "\n\n" . $message;
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent);
else my_contact_form_generate_response("error", $message_unsent);
}
}
} else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
I keep getting the "not human error". I tried making $outcome an array and all kind of operators but nothing works. When I give the $outcome a fixed value like = "2"; everything works fine, but I want it to be a random number. Some help would be much appreciated.
Upvotes: 0
Views: 37
Reputation: 34
If I understand your code right, you are not saving those random numbers, right? So how could you get the correct comperison, when you send the answer to a previous generated set of random numbers when you just generate new ones?
A possible solution may be to save those values in a session variable.
session_start();
$_SESSION['outcome'] = $outcome;
and compare it later with this variable, but make sure it is not overwritten by a new generated set of random numbers.
if($_POST['message_human'] == $_SESSION['outcome']){
//correct
}
Upvotes: 1