PHP验证码函数

今天做网页时发现需要使用php里面的验证码函数,照猫画虎写了一个,默认用的是系统字体,可以通过修改fontfamily路径使用自定义字体

<?php
	//$fontFamily = 'C:\phpstudy_pro\WWW\shop15.com\shop15\home\msyh.ttf';
	//vcode($fontFamily);
	vcode();
	//函数验证码
	//参数:字体,宽,高,验证码字符数
	function vcode($fontFamily = '',$w = 100,$h = 40,$num = 4){
		//1.创建画布,宽:$w,高:$h
		$img = imagecreatetruecolor($w,$h);
		//2.分配颜色,背景色以及边框色
		$backColor = imagecolorallocate($img,mt_rand(200,255),
					mt_rand(200,255),mt_rand(200,255));
		$red = imagecolorallocate($img,255,0,0);
		//3.绘画
			//为图片填充背景色
			imagefill($img,0,0,$backColor);
			//为图片创建红色边框,数字是左上角(x,y)以及右下角(x,y)
			imagerectangle($img,0,0,$w-1,$h-1,$red);
			//干扰线
			for($i = 0; $i < 10; $i++){
				//得到干扰线颜色
				$lineColor = imagecolorallocate($img,mt_rand(150,255),
					mt_rand(150,255),mt_rand(150,255));
				//绘制干扰线,起点+终点
				imageline($img,mt_rand(2,$w-2),mt_rand(2,$h-2),
						mt_rand(2,$w-2),mt_rand(2,$h-2),$lineColor);
			}
			//干扰点
			for($i = 0; $i < 300; $i++){
				//得到干扰线颜色
				$pixelColor = imagecolorallocate($img,mt_rand(100,255),
					mt_rand(100,255),mt_rand(100,255));
				//绘制干扰线,坐标,颜色
				imagesetpixel($img,mt_rand(2,$w-2),mt_rand(2,$h-2),$pixelColor);
			}
			//验证码字符
				//定义验证码字符
				$str = '0123456789abcdefghijklmnopqrstuvwxyz
						ABCDEFGHIJKLMNOPQRSTUVWXYZ';
				//获取验证码字符
				$len = '';
				for($i = 0; $i < $num; $i++){
					$len .= $str[mt_rand(0,strlen($str)-1)];
				}
				//循环将字符写入
				if(empty($fontFamily)){
					//使用系统字体
					for($i = 0; $i < $num; $i++){
						$fontColor = imagecolorallocate($img,mt_rand(100,200),
									mt_rand(100,200),mt_rand(100,200));
						$x = $w / $num * $i + mt_rand(3,8);
						$y = mt_rand(10,$h/2);
						//img后字体大小,后面是左上角坐标
						imagechar($img,mt_rand(3,5),$x,$y,$len[$i],$fontColor);
					}
				}else{
					//使用传入的字体库
					for($i = 0; $i < $num; $i++){
						$fontColor = imagecolorallocate($img,mt_rand(100,200),
									mt_rand(100,200),mt_rand(100,200));	
						$x = $w / $num * $i + mt_rand(3,8);
						$y = mt_rand($h/2,$h-2);
						//参数 img,字体大小,倾斜角度
						imagefttext($img,mt_rand($h/3,$h/2),mt_rand(0,45),
						$x,$y,$fontColor,$fontFamily,$len[$i]);
					}
				}
		//4.告诉浏览器图片相关信息
		header('Content-type:image/jpeg');
		//5.输出图片到浏览器
		imagejpeg($img);
		//6.释放资源
		imagedestroy($img);
	}
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值