Captcha Refresh(未来的Ajax)

时间:2012-09-23 12:23:32

标签: php ajax submit captcha

我已经在这里和那里进行了几次调查,并使用我希望在我的更大项目中实现的会话制作了自己的验证码。在联系/发送电子邮件部分,应像其他地方一样使用验证码,以防止垃圾邮件重复。

问题 - 如果您错过了验证码和点击后退按钮,则验证码不会刷新。这和它的糟糕程度一样好,而使用ajax意味着验证码不会刷新页面,验证码也不会自行刷新。由于验证码是在不同的文件中制作的,我想再次调用同一个文件应该可以解决问题。

解决方案 - 我想要一个3尝试系统,如果验证码没有被猜到3次,那么页面就会被刷新。

PHP CAPTCHA代码:

<?php
session_start();
$text = rand(10000, 99999);
$_SESSION['captcha'] = $text;
// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 25, 25, 25);
$black = imagecolorallocate($im, 0, 0, 255);
imagefilledrectangle($im, 0, 0, 399, 29, $white);


$font = 'Candara.ttf';

imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

imagepng($im);
imagedestroy($im);
?>

HTML测试代码:

<form action="submit.php" method="post">
Message: <textarea name="comment"></textarea><br>
Captcha: <input type="text" name="val_code"/>&nbsp;&nbsp;<img src="generate captcha.php"><br>
<input type="submit" value="Submit" name="Submit"/>
</form>

提交PHP代码:

<?php
session_start();
if($_POST["val_code"] != $_SESSION['captcha'] OR $_SESSION['captcha'] == '') {
echo "<b><font style='color: purple'>Wrong captcha value. Please go back and resend the message</font></b>";
}
else
{
echo "<b><font style='color: green'>Thank you for your message!</font></b>";
}
?>

1 个答案:

答案 0 :(得分:1)

您需要使用能够跟踪尝试次数的计数器。此外,请确保取消设置验证码,以使其无法重复使用。请参阅以下代码:

PHP CAPTCHA代码:

<?php
session_start();
if ($_SESSION['tries'] < 2 && $_SESSION['captcha']) {
    $text = $_SESSION['captcha'];
} else {
    $_SESSION['tries'] = 0;
    $text = rand(10000, 99999);
    $_SESSION['captcha'] = $text;
}
// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 25, 25, 25);
$black = imagecolorallocate($im, 0, 0, 255);
imagefilledrectangle($im, 0, 0, 399, 29, $white);


$font = 'Candara.ttf';

imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

imagepng($im);
imagedestroy($im);
?>

PHP代码:

<?php
session_start();
if ($_SESSION['tries']>=2) {
   echo "<b><font style='color: purple'>Captcha has expired! You need to go back and reload the page</font></b>";
} else if($_POST["val_code"] != $_SESSION['captcha'] OR $_SESSION['captcha'] == '') {
echo "<b><font style='color: purple'>Wrong captcha value. Please go back and resend the message</font></b>";
$_SESSION['tries']++;
}
else
{
unset($_SESSION['captcha']);
unset($_SESSION['tries']);
echo "<b><font style='color: green'>Thank you for your message!</font></b>";
}
?>

html测试代码:

<form action="submit.php" method="post">
Message: <textarea name="comment"></textarea><br>
Captcha: <input type="text" name="val_code"/>&nbsp;&nbsp;<img src="generate captcha.php" /><br>
<input type="submit" value="Submit" name="Submit" />
</form>