php中验证码类

<?php
<img src="https://img-blog.csdn.net/20160902150110188?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
Class Verify
{
	//一些变量
	//高
	protected $height;
	//宽
	protected $width;
	//图片类型
	protected $imgType;
	//文字类型
	protected $codeType;
	//文字的个数
	protected $num;
	//验证码字符串
	protected $verifyCode;
	//保存验证码的资源
	protected $res;
	
	
	
	//初始化这些变量
	public function __construct($width=100,$height=50,$imgType='png',$codeType='numOnly',$num=4)
	{
		$this->width = $width;
		$this->height = $height;
		$this->imgType = $imgType;
		$this->codeType = $codeType;
		$this->num = $num;
		$this->verifyCode = $this->createVerifyCode();
	}
	//成员方法
	//1.创建验证码字符串
	public function createVerifyCode()
	{
		
		switch ($this->codeType) {
			case 'letterOnly':
				$str = implode('',array_rand(array_flip(range('a','z')),$this->num));
				break;
			case 'numOnly':
				$str = implode('',array_rand(range(0,9),$this->num));
				break;
			case 'mix':
				$string = 'ABCDEFGHGKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
				$str = substr(str_shuffle($string),$this->num);
				break;
		}
		return $str;
	}
	//2.输出图片
	public function outImg()
	{
		//创建画布
		$this->createImg();
		//背景分配颜色
		$this->fillBgColor();
		//画干扰点
		$this->fillPix();
		//画干扰线
		$this->fillArc();
		//写字
		$this->writeFont();
		//输出类型及图片
		$this->output();
	}
	function createImg()
	{
		$this->res = imagecreatetruecolor ($this->width,$this->height);
	}
	function fillBgColor()
	{
		imagefill($this->res,0,0,$this->lightColor());
	}
	function lightColor()
	{
		return imagecolorallocate($this->res,mt_rand(130,255),mt_rand(130,255),mt_rand(130,255));
	}
	function darkColor()
	{
		return imagecolorallocate($this->res,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
	}
	function fillPix()
	{
		$num = $this->pixNum();
		for ($i=0;$i<$num;$i++) {
			imagesetpixel($this->res,mt_rand(0,$this->width),mt_rand(0,$this->height),$this->darkColor());
		}		
	}
	function pixNum()
	{
		$num = ceil(($this->width * $this->height)/$this->num/10);
		return $num;
	}
	function fillArc()
	{		
		for ($i=0;$i<6;$i++) {
			imagearc ($this->res,mt_rand(10,$this->width-10),mt_rand(10,$this->height-10),mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,180),mt_rand(181,360),$this->darkColor());
		}		
	}
	function writeFont()
	{
		for ($i=0;$i<$this->num;$i++) {
			$width = ceil($this->width / $this->num);
			$x = $width * $i; 
			$y = mt_rand(5,$this->height-20);
			$c = $this->verifyCode[$i];
			imagechar ($this->res,5,$x,$y,$c,$this->darkColor());
		}
	}
	function output()
	{
		$func = 'image'.$this->imgType;
		$mime = 'Content-type:image/'.$this->imgType;
		header($mime);
		$func($this->res);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值