PHP实现验证码
第一步:创建一个画布
第二步:创建颜色
第三步:准备字符
第四步:往 画布上写字符
第五步:画干扰线(点)
第六步:输出格式
第七步:输出图片
第八步:销毁资源
<?phpverify();functionverify($width=100,$height=40,$num=5,$type=3){//1创建画布$image=imagecreatetruecolor($width,$height);//2创建颜色//因为后边总是用,所以写了两个函数,分别是lightColor(浅颜色)、deepColor(深颜色)//3创建字符//这里是自己选择的类型,1就是纯数字,2就是纯小字母,3就是数字大小写字母的混合switch($type){case1://定义字符串$str="0123456789";//打乱字符串$strNew=str_shuffle($str);//截取$num个$string=substr($strNew,0,$num);break;case2://定义字符$arr=range('a','z');//打乱字符串数组shuffle($arr);//截取$tmp=array_slice($arr,0,$num);//连成字符串$string=join('',$tmp);break;case3:$str="23456789abcdefghjklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";$string=substr(str_shuffle($str),0,$num);break;}//给背景填充浅颜色//背景颜色太深的话验证码就看不清了imagefilledrectangle($image,0,0,$width,$height,lightColor($image));//4往画布上写入字符for($i=0;$i<$num;$i++){//因为我们设定的是输出5个字符,所以$i是小于的$num//floor是取整,$width/$num把宽度分了$num块地,*$i是一个字符占一块地,以免全都堆在一块看不出来$x=floor($width/$num)*$i;$y=mt_rand(10,$height-20);imagechar($image,5,$x,$y,$string[$i],deepColor($image));}//5画干扰线、点//干扰线for($i=0;$i<$num;$i++){imagearc($image,mt_rand(10,$width),mt_rand(10,$height),mt_rand(10,$width),mt_rand(10,$height),mt_rand(0,10),mt_rand(0,270),deepColor($image));}//干扰点for($i=0;$i<50;$i++){imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),deepColor($image));}ob_clean();//擦除缓冲区//6告诉浏览器输出格式:pngheader("Content-type:image/png");//7输出图片imagepng($image);//8销毁imagedestroy($image);return$string;//echo$string;}//设置深浅颜色functionlightColor($image){returnimagecolorallocate($image,mt_rand(120,255),mt_rand(120,255),mt_rand(120,255));}functiondeepColor($image){returnimagecolorallocate($image,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));}?>
特别说明:
ob_clean();//擦除缓冲区
之前是没有加上这个的,结果就告诉我“因存在错误而无法显示”,如下图:
不过幸运的是,在百度上找到答案了:https://blog.csdn.net/ghbfgb/article/details/50845075。加上之后,就很轻易的解决了这个问题,现在的效果是这样的:
好了。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。