上一篇博文中实现了一个完全基于前端的验证码,不过由于其完全是由文本实现,所以安全性上有很大问题。当然一般情况下的验证码都是图片格式的,在网上搜索学习了一番之后,发现图片格式的验证码的实现步骤一般为:
1. 采用<img>标签作为验证码的容器,其src属性值为生成验证码图片的链接地址(PHP、JSP等);
2. 服务器端生成验证码图片(即1中的链接)的同时,在session中放入验证码的真实值;
3. 在验证码的判断逻辑中检查前台传入的输入和session中验证码值;
4. 如果需要的话,可以为界面中的验证码添加刷新功能。
下面的代码是通过PHP实现的算术题式图片验证码,备用:
前台HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>验证码</title> <style type="text/css"> #code { cursor: pointer; } </style> </head> <body> </body> <form action="check.php" method="post"> <input type="text" name="input" /><img id="code" alt="点击刷新" title="点击刷新" src="code.php" /><br /> <input type="submit" value="确定" /> </form> <script type="text/javascript"> document.getElementById("code").onclick = function() { this.src = "code.php?t=" + Math.random(); } </script> </html>验证码图片生成code.php:
<?php $cimg = imagecreate(100, 30); imagecolorallocate($cimg, 14, 114, 180); // background color $red = imagecolorallocate($cimg, 255, 0, 0); $num1 = rand(1, 99); $num2 = rand(1, 99); session_start(); $_SESSION['code'] = $num1 + $num2; imagestring($cimg, 5, 5, 5, $num1, $red); imagestring($cimg, 5, 30, 5, "+", $red); imagestring($cimg, 5, 45, 5, $num2, $red); imagestring($cimg, 5, 70, 5, "=?", $red); header("Content-type: image/png"); imagepng($cimg) ?>判别逻辑check.php:
<?php
session_start();
if ($_SESSION['code'] == $_POST['input']) {
echo "Pass!";
} else {
echo "Wrong input!";
}
?>
如果需要换成Java实现,只需要将验证码生成有PHP实现换成Java实现即可,大同小异。