验证码在WEB应用中非常重要,通常用来防止用户恶意提交表单,如恶意注册和登录,论坛恶意灌水等。
PHP生成验证码图片
PHP生成验证码原理:使用PHP的GD库,生成一张带验证码的图片,并将验证码存在Session中。PHp生成验证码的大致流程有:
生成一张图片
为图片设置背景颜色
设置字体颜色和样式
产生随机的验证码
把产生的验证码的每个字符处理后画到图片上
加入噪点和干扰线
输出图片
释放图片所占内存
session_start();
getCode(4,60,20);
function getCode($len,$width,$height){
$code = '';
for($i=0;$i
$code .= rand(0,9);
}
//将生成的验证码写入session,验证时用
$_SESSION['chkcode'] = $code;
//创建图片,定义颜色值
header("Content-type:image/png");
$im = imagecreate($width,$height);
$black = imagecolorallocate($im,0,0,0);
$gery = imagecolorallocate($im,200,200,200);
$bgcolor = imagecolorallocate($im,255,255,255);
//填充背景
imagefill($im,0,0,$grey);
//画边框
imagereactangle($im,0,0,$width-1,$height-1,$black);
//随机回执两条虚线,起干扰作用
$style = array($black,$black,$black,$black,$black,$grey,$grey,$grey,$grey,$grey);
imagesetstyle($im,$style);
$y1 = rand(0,$height);
$y2 = rand(0,$height);
$y3 = rand(0,$height);
$y4 = rand(0,$height);
imageline($im,0,$y1,$width,$y3,IMG_COLOR_STYLED);
imageline($im,0,$y2,$width,$y4,IMG_COLOR_STYLED);
//在画布上随机生成大量黑点,起干扰作用
for($i=0;$i<80;$i++){
imagesetpixel($im,rand(0,$width),rand(0,$height),$black);
}
//将数字随机显示在画布上,字符的水平间距和位置都按一定波动范围随机生成
$strx = rand(3,8);
for($i=0;$i
$strpos = rand(1,6);
imagestring($im,6,$strx,%strpos,%substr($code,$i,1),$black);
$strx +=rand(8,12);
}
imagepng($im);//输出图片
imagedestory($im);//释放图片所占内存
}
将上述代码保存为code_num.php,以便调用。
Ajax刷新和验证
验证码生成后,我们要在实际的项目中应用,通常我们使用ajax可以实现点击验证码时刷新生成新的验证码(有时生成的验证码肉眼很难识别),即“看不清换一张”。填写验证码后,还需要验证所填验证码是否正确,验证的过程是要后台程序来完成,但是我们也可以通过ajax来实现无刷新验证。
新建一个前段页面index.html,载入jquery,同时在body中加入验证码表单元素:
验证码:
html代码中,
$(function(){
//数字验证
$("$getcode_num").click(function(){
$this.attr("src","code_num.php?"+Math.random());
});
...
});刷新验证码,其实就是重新请求了验证码生成程序,这里要注意的是调用code_num.php时要带上随机参数防止缓存。接下来填写好验证码之后,点“提交”按钮,通过$.post(),前端向后台chk_code.php发送ajax请求。
$(function(){
...
$("#chk_num").click(function(){
var code_num = $("#code_num").val();
$.post("chk_code.php?act=num",{code:code_num},function(msg){
if(msg==1){
alert("验证码正确!");
}else{
alert("验证码错误!");
}
});
});
});
后台chk_code.php验证:session_start();
$code = trim($_POST['code']);
if($code==$_SESSION['chkcode']){
echo '1';
}
后台根据提交的验证码与保存在session中的验证码比对,完成验证。