我正在尝试编写一个简单的数学验证码函数来验证一个表单,该表单将允许用户在博客上发布特定文章.
功能:
function create_captcha($num1, $num2) {
$num1 = (int)$num1;
$num2 = (int)$num2;
$rand_num_1 = mt_rand($num1, $num2);
$rand_num_2 = mt_rand($num1, $num2);
$result = $rand_num_1 + $rand_num_2;
return $result;
}
形成:
<h2 class="email_users_headers">Post Article</h1>
<form action="" method="post" id="post_blog_entry">
<input type="text" name="title" id="title" placeholder="title... *"><br>
<textarea name="content" id="content" cols="30" rows="5" placeholder="content... *"></textarea><br>
<?php echo create_captcha(1, 20) . ' + ' . create_captcha(1, 20) . ' = '; ?>
<input type="text" name="captcha_results" size="2">
<input type="hidden" name='num1' value='<?php echo create_captcha(1, 20); ?>'>
<input type="hidden" name='num2' value='<?php echo create_captcha(1, 20); ?>'>
<input type="submit" name="publish" value="post entry" id="publish">
</form>
验证码验证:
if (empty($_POST['captcha_results']) === true) {
$errors[] = 'Please enter captcha';
} else {
if ($_POST['captcha_results'] != $_POST['num1'] + $_POST['num2']) {
$errors[] = 'Incorrect captcha';
}
}
我知道这是完全错误的,因为无论输入结果总是不正确.有人能指出我正确的方向,因为我没有任何PHP经验.
解决方法:
每次运行create_captcha(1,20)时,它都会生成不同的值.
> create_captcha(1,20) – 3 7 = 10
> create_captcha(1,20) – 6 11 = 17
…
在你的表格中你称之为4次.
我想你应该这样做:
$num1 = create_captcha(1, 20);
$num2 = create_captcha(1, 20);
并在表单中使用此值:
<textarea name="content" id="content" cols="30" rows="5" placeholder="content... *"></textarea><br>
<?php echo $num1 . ' + ' . $num2 . ' = '; ?>
<input type="text" name="captcha_results" size="2">
<input type="hidden" name='num1' value='<?php echo $num1; ?>'>
<input type="hidden" name='num2' value='<?php echo $num2; ?>'>