在很多表单场景中,经常会看到输入验证码的地方,本文介绍如何通过php生成验证码并对用户输入的验证码进行验证。
首先我们在html页面中写一个显示及输入验证码的表单:
<h1>验证码</h1> <input type="text" name="verify"/><img src="verify.php" alt=""/> <input type="button" id="submitVerify" value="验证"/>其中img标签的src为我们生成验证码的php,verify.php代码如下:
<?php header("Content-Type:application/json;charset=UTF-8"); session_start(); //生成一个随机字符串,默认$type=1,默认$length=4 function buildRandomString($type=3,$length=4){ if($type==1){ //$type为1时产生纯数字验证码 $chars=join("",range(0,9)); }else if($type==2){ //$type为2时产生纯字母验证码 $chars=join("",array_merge(range("a","z"),range("A","Z"))); }else if($type==3){ //$type为3时产生字母数字混合验证码 $chars=join("",array_merge(range("a","z"),range("A","Z"),range(0,9))); } if($length>strlen($chars)){ exit("字符串长度不够"); } $chars=str_shuffle($chars); $chars=substr($chars,0,$length); return $chars; } //生成验证码的php,通过GD库做验证码 function verifyImage($type=3,$length=4){ //创建画布 $width=80; $height=28; $image=imagecreatetruecolor($width,$height); $white=imagecolorallocate($image,255,255,255); $black=imagecolorallocate($image,0,0,0); //用填充矩形填充画布 imagefilledrectangle($image,1,1,$width-2,$height-2,$white); $chars=buildRandomString($type,$length); $_SESSION['verify']=$chars; $fontfiles=array("msyh.ttf" ,"msyhbd.ttf" ,"SIMLI.TTF" ,"simsun.ttc" ,"SIMYOU.TTF" ,"STZHONGS.TTF"); for($i=0;$i<$length;$i++){ $size=mt_rand(14,18); $angle=mt_rand(-15,15); $x=5+$i*$size; $y=mt_rand(20,26); $fontfile="fonts/".$fontfiles[mt_rand(0,count($fontfiles)-1)]; $color=imagecolorallocate($image ,mt_rand(50,90) ,mt_rand(80,200) ,mt_rand(90,180)); $text=substr($chars,$i,1); imagettftext($image,$size,$angle,$x,$y,$color,$fontfile,$text); } //加入一些点作为干扰元素 for($i=0;$i<50;$i++){ imagesetpixel($image ,mt_rand(0,$width-1) ,mt_rand(0,$height-1) ,$black); } ob_clean(); header("Content-Type:image/gif"); imagegif($image); imagedestroy($image); } verifyImage();
在上面的代码中,$fontfiles中的字体文件样放在这些php文件的同级目录下的fonts文件夹中,否则注意修改引用fonts文件的路径。fonts文件夹中的文件可以在C盘windows目录下,再到Font文件夹中粘贴几个字体文件放入fonts文件夹内,我粘了6个字体文件。没有fonts文件夹及里面的字体文件的话验证码不显示。
还要注意在使用php的SESSION之前一定要先开启session,即如下这句代码:
session_start();
否则无论是对php的SESSION进行存还是取的操作,都不会成功。
这样我们就生成了gif格式的验证码图片
接下来就是验证用户输入的验证码是否正确了,我们通过ajax请求getVerify.php
$("#submitVerify").click(function(){ var verify=$("input[name='verify']").val(); $.ajax({ type:"post", url:"getVerify.php", data:'verify='+verify, dataType:"json", success:function(data){ console.log("请求成功!"); console.log(data); }, error:function(err){ console.log("请求失败!"); console.log(err); } }); });getVerify.php代码如下:
<?php /* 错误代码 701--验证码为空 702--验证码错误 */ require_once 'outputInfo.php'; session_start(); $verify=$_REQUEST['verify']; if($verify==NULL){ outputing(701,'请输入验证码'); }else{ $sessionVerify=strtolower($_SESSION['verify']); $verify=strtolower($verify); if($verify==$sessionVerify){ outputing(200,'验证成功'); }else{ outputing(702,'验证码错误'); } }其中引入了outputInfo.php,该php定义了错误提示函数,代码代码如下:
<?php //用于提示错误信息及错误码的函数 function outputing($status,$reason){ $output=[]; $output['resultCode']=$status; $output['resultMsg']=$reason; echo json_encode($output); return; }在验证用户输入的验证码时,对用户输入值做了小写转换处理,不管用户输入大写还是小写字母,都能正确验证出来,效果如下: