PHP图像处理绘图、水印、验证码、图像压缩技术实例总结(2)
2019-01-22 15:21
互联网
3、验证码
封装的验证码类?
<?php/** 生成验证码*/classCaptcha{private$_width= 100;private$_height= 25;private$_number= 4;//显示的验证码的字符个数private$_font= 15;//验证码字体大小private$_fontfile='STXINWEI.TTF';//创建验证码图像publicfunctionmakeImage(){# 1. 创建图像资源(画布)$image= imagecreatetruecolor($this->_width,$this->_height);//随机填充颜色//mt_rand(0,255) 生成一个更具有唯一性的随机数 #000 255$color= imagecolorallocate($image,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));imagefill($image,0,0,$color);# 2.绘制文字$code=$this-> makeCode();//随机生成验证码文字 ab3g$color= imagecolorallocate($image,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));for($i=0;$i<$this->_number;$i++){imagettftext($image,$this->_font,mt_rand(-30,30),$i*($this->_width/$this->_number)+5,20,$color,$this->_fontfile,$code[$i]);}# 3.绘制15条干扰线条for($i=0;$i<10;$i++){$color= imagecolorallocate($image,mt_rand(100,150),mt_rand(100,150),mt_rand(100,150));imageline($image,mt_rand(0,$this->_width),mt_rand(0,$this->_height),mt_rand(0,$this->_width),mt_rand(0,$this->_height),$color);}# 4.设置100个干扰像素点for($i=0;$i<100;$i++){imagesetpixel($image,mt_rand(0,$this->_width),mt_rand(0,$this->_height),$color);}# 5.将验证码保存起来吗,便于后面再其他地方使用//只能使用session来存储,session明天就会讲到session_start();$_SESSION['captcha'] =$code;//在浏览器输出、显示一下header("Content-Type:image/png");imagepng($image);imagedestroy($image);}/*** 随机产生随机数*/publicfunctionmakeCode(){# 获得字母的范围(大写字母、小写字母)$lower= range('a','z');//创建从小a到小z字符范围的数组$upper= range('A','Z');//创建从大A到大Z范围的数组$number= range(3,9);//创建从3到9之间的数字//将上面的三个数组合并成一个数组$code=array_merge($lower,$upper,$number);# 打乱数组元素的顺序shuffle($code);//随机从上面的数组中筛选出n个字符,需要通过下标来取数组的元素$str='';for($i=0;$i<$this->_number;$i++){$str.=$code[$i];}return$str;}/*** 验证用户输入的验证码和我们生产的验证码是否一致* @param [str] $input [输入验证码值]* @return*/publicfunctioncheckCode($input){session_start();if(strtolower($code) ==strtolower($_SESSION['captcha'])){//说明验证码正确//echo '验证码正确';returntrue;}else{//echo '验证码错误';returnfalse;}}}?>
实例 - 验证码验证(结合上面的验证类)
html页面?
<formaction="captcha.php?act=verify"method="post">验证码:<inputtype="text"name="captcha"><imgsrc="captcha.php?act=show"><br><inputtype="submit"value="提交"></form>
验证码检测 captcha.php 页面?
//接收地址栏上面的参数if($_GET['act']=='verify'){//说明是提交的表单//接收表单中用户输入的内容$code=$_POST['captcha'];//和创建的验证码进行比较session_start();//将用户输入的验证码 和 我们创建的统一小写之后再进行比较if(strtolower($code) ==strtolower($_SESSION['captcha'])){//说明验证码正确echo'验证码正确';}else{echo'验证码错误';}}elseif($_GET['act']=='show'){//说明需要显示一个图片require'Captcha.class.php';$captcha=newCaptcha();$captcha-> makeImage();}