$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); $type=1; $length=4; $chars=buildRandomString($type,$length); $sess_name="verify"; $_SESSION['sess_name']=$chars; $fontfiles=array("MSYH.TTF","MSYHBD.TTC","SIMLI.TTF","SIMSUN.TTC","SIMYOU.TTF","STZHONGS.TTF"); //这是字体,cmd 输入fonts可以查看到自己电脑里面的字体 然后拷贝到自己项目的文件夹下 $fontfile="../fonts/".$fontfiles[mt_rand(0,count($fontfiles)-1)]; //随机取出一个字体格式 0-数组长度减一 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); $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); } $pixel=50; if($pixel) { for($i=0;$i<50;$i++) { imagesetpixel($image,mt_rand(0,$width-1),mt_rand(0,$height-1),$black) ; } //这个for循环的目的是画出小黑点 } $line=10; if($line) { for($i=1;$i<10;$i++) { imageline($image,mt_rand(0,$width-1),mt_rand(0,$height-1),mt_rand(0,$width-1),mt_rand(0,$height-1),$color); //画的横线也为随机颜色 } } header("content-type:image/gif"); imagegif($image); imagedestory($image);
function buildRandomString($type=1,$length=4) { //产生随机字符串 //$type = 1; //$length = 4;//产生4位验证码 if ($type == 1) { $chars = join("", range(0, 9)); } elseif ($type == 2) { $chars = join("", array_merge(range("a", "z"), range("A", "Z"))); } elseif ($type == 3) { $chars = join("", array_merge(range("a", "z"), range("A", "Z"), range("0", "9"))); } if ($length > strlen($chars)) //产生的长度不够 { exit("字符串长度不够"); } $chars = str_shuffle($chars);//随意打乱 return substr($chars, 0, $length); }//函数在此结束
php 验证码实现
最新推荐文章于 2021-03-09 23:57:16 发布