《PHP中产生验证码函数封装》

<?php

//此函数可以实现纯数字、数字+字母和中文的验证码
/**
*$width  $height创建的画布宽高
*$type   产生验证码类型(1:纯数字验证码  2:纯字母验证码3:数字+字母验证码4:中文验证码)
*$codeName   保存在session中的验证码名
*$pixel  产生的干扰点个数
*$line   产生的干扰线个数
*$arc    产生的干扰弧个数
*$fontfile  字体类型
*/

	function getVerify($width=200,$height=50,$type=1,$length=4,$codeName='verifyCode',$pixel=50,$line=0,$arc=0,$fontfile='fonts/SIMYOU.TTF'){
		//创建画布
		//$width=200;
		//$height=50;
		//创建画布
		$image=imagecreatetruecolor($width, $height);
		//创建画布背景图颜色
		$white=imagecolorallocate($image, 255, 255, 255);
		//创建填充矩形
		imagefilledrectangle($image, 0, 0, $width, $height, $white);
		//得到随机眼色
		function getRandColor($image){
			imagecolorallocate($image, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
		}
		/*产生验证码类型(默认产生4位的数字验证码)
		*1-数字
		*2-字母
		*3-数字+字母
		*4-汉子
		*/
		//$type=4;
		//$length=4;
		switch ($type) {
			case 1:
				//数字	
				$string=join('',array_rand(range(0, 9),$length));
				//echo $string;
			break;
			case 2:
				//字母
				$string=join('',array_rand(array_flip(array_merge(range('a', 'z'),range('A', 'Z'))),$length));//array_merge()将多个数组连接形成一个新的数组
			break;
			case 3:
				//数字+字母
				$string=join('',array_rand(array_flip(array_merge(range('a', 'z'),range('A', 'Z'),range(0, 9))),$length));
				//echo $string;
			break;
			case 4:
				//汉字
				$str="开,始,的,官,方,科,技,的,说,法,就,大,概,时,间,的,风,格,大,发,光,火,是,多,个,大,家,分,工,和,实,际,的,风,格";
				$arr=explode(',', $str);
				$string=join(array_rand(array_flip($arr),$length));

			break;
			default:
				exit("非法参数");
		}

		for($i=0;$i<$length;$i++){
			$size=mt_rand(20,28);
			$angle=mt_rand(-15,15);
			$x=20+ceil($width/$length)*$i;
			$y=mt_rand(ceil($height/3),$height-20);
			$color=getRandColor($image);
			//$fontfile='fonts/SIMYOU.TTF';
			//中文  substr   mb_substr
			$text=mb_substr($string, $i,1,'utf-8');
			imagettftext($image, $size, $angle, $x, $y, $color,  $fontfile, $text);
		}
		//将验证码存入session
		$_SESSION[$codeName]=$string;

		//$pixel=50;
		//$line=0;
		//$arc=0;
		//添加像素干扰元素
		if($pixel>0){
			for($i=1;$i<=$pixel;$i++){
				imagesetpixel($image, mt_rand(0,$width), mt_rand(0,$height), getRandColor($image));
			}
		}

		//添加线段干扰元素
		if($line>0){
			for($i=1;$i<=$line;$i++){
				imageline($image, mt_rand(0,$width), mt_rand(0,$height),  mt_rand(0,$width), mt_rand(0,$height), getRandColor($image));
			}
		}

		//添加弧线
		if($arc>0){
			for($i=1;$i<=$arc;$i++){
				imagearc($image, mt_rand(0,$width/2), mt_rand(0,$height/2), mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,360), mt_rand(0,360), getRandColor($image));
			}
		}
		header("content-type:image/png");
		imagepng($image);
		imagedestroy($image);
}
//getVerify();
?>
友情提示小伙伴儿:添加自己的个性字体时,注意一下路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值