1

我在这里和那里遵循了一些 tuts 并制作了我自己的验证码会话,我想在我的更大项目中实施。验证码应该像其他地方一样在联系/发送电子邮件部分使用,以防止垃圾邮件重复。

问题 - 如果您错过了验证码并点击返回按钮,验证码不会刷新。这既好又坏,使用 ajax 意味着验证码不会刷新页面,验证码不会自行刷新。由于验证码是在不同的文件中制作的,我想再次调用同一个文件应该可以解决问题。

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

PHP验证码:

<?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>";
}
?>
4

1 回答 1

1

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

PHP验证码:

<?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>
于 2012-09-23T12:53:51.363 回答