在<head> 标记中包含此内容
<script type="text/javascript">
$(document).ready(function() {
// refresh captcha
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha()
{
document.getElementById('captcha').src="captcha.php?rnd=" + Math.random();
}
});
</script>
此代码在您希望验证码图像和刷新图标(获取合适的刷新图像并将其重命名为 refresh.jpg)出现的任何位置。请记住此代码和上面的代码(在 <script> 标记内)应该在同一页面上,这样验证码才能正常工作。
<img src="captcha.php" alt="" id="captcha" />
Type the word:
<input name="user_captcha" type="text" id="captcha-code">
<img src="refresh.jpg" alt="" id="captcha-refresh" />
然后创建一个名为 captcha.php 的文件(它会根据要求生成 png 格式的验证码图像)。
<?php
session_start();
header("Content-type: image/png");
$word_1 = '';
for ($i = 0; $i < 4; $i++)
{
$word_1 .= chr(rand(97, 122));
}
$_SESSION['random_number'] = $word_1;
$dir = "./";
$image = imagecreatetruecolor(165, 50);
$font = "whatever.ttf"; // font style you may give any you have / prefer
$color = imagecolorallocate($image, 0, 0, 0);// color
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image, 0,0, 709, 99, $white);
imagettftext ($image, 22, 0, 45, 30, $color, $dir.$font, $_SESSION['random_number']);
imagepng($image);
?>
最后你必须通过比较$_POST['user_captcha']和$_SESSION['random_number']来检查用户输入和验证码中出现的文本是否匹配,无论你在哪里传递表单的其他值。
N。 B.:不忘记添加 session_start();任何你想要验证码图像的地方。