我是编码新手,所以这可能是一个愚蠢的错误,但我就是无法弄清楚出了什么问题。我制作了一个带有功能的电子邮件表单,用于检查是否是人发送消息。他们必须回答一个用随机数生成的简单数学问题。但是当我尝试检查输入是否正确时,出现了问题。
我正在使用的代码的相关部分:首先,我生成两个随机数,计算正确的结果并将答案转换为变量:
$number = array( mt_rand(1,5), mt_rand(6,10) );
$outcome = $number[1] - $number[0];
$human = $_POST['message_human'];
放置答案的部分:
<label for="message_human">
<input type="text" style="width: 44px;" placeholder="…" name="message_human"> + <?php echo $number[0];?> = <?php echo $number[1];?>
</label>
检查答案是否正确并执行操作的部分:
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 . "nn" . $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);
我一直得到"非人为错误"。我尝试将$outcome数组和所有类型的运算符制作,但没有任何效果。当我给$outcome一个固定值时,例如 = "2";一切正常,但我希望它是一个随机数。一些帮助将不胜感激。
理解你的代码正确,你就不会保存那些随机数,对吧?那么,当你将答案发送到以前生成的随机数集时,你怎么能得到正确的比较,而你只是生成新的随机数?
一种可能的解决方案是将这些值保存在会话变量中。
session_start();
$_SESSION['outcome'] = $outcome;
并稍后将其与此变量进行比较,但请确保它不会被一组新生成的随机数覆盖。
if($_POST['message_human'] == $_SESSION['outcome']){
//correct
}