php驗證碼類

可直接運行查看效果,代碼附了大量備註,若有疑問可留言交流。 php

<?php

$code = new Code();
$code->outImage();

class Code
{
	//驗證碼個數
	protected $number;
	//驗證碼類型
	protected $codeType;
	//圖像寬度
	protected $width;
	//圖像高度
	protected $heigth;
	//圖像資源
	protected $image;
	//驗證碼字符串
	protected $code;
	
	public function __construct($number=4,$codeType=2,$width=100,$heigth=30)
	{
		//初始化成員屬性
		$this->number = $number;
		$this->codeType = $codeType;
		$this->width = $width;
		$this->heigth = $heigth;

		//生成驗證碼
		$this->code = $this->createCode();
	}

	public function __destruct()//析構函數銷燬image
	{
		imagedestroy($this->image);
	}

	public function __get($name)//直接獲取code以便驗證
	{
		if($name == 'code')
		{
			return $this->code;
		}
		return false;
	}

	protected function createCode()
	{
		//判斷類型
		switch ($this->codeType) {
			case 0://純數字
				$code = $this->getNumberCode();
				break;

			case 1://純字母
				$code = $this->getCharCode();
				break;

			case 2://混合
				$code = $this->getNumCharCode();
				break;
			
			default:
				die('不支持這種驗證碼');
		}
		return $code;
	}

	//join函數將數組整合爲字符串
	//range按要求生成數組
	//substr按要求切割字符串
	//str_shuffle打亂字符順序
	//strtoupper轉大寫
	protected function getNumberCode()
	{
		$str = join('',range(0,9));
		return substr(str_shuffle($str),0,$this->number);
	}
	protected function getCharCode()
	{
		$str = join('',range('a','z'));
		$str = $str.strtoupper($str);
		return substr(str_shuffle($str),0,$this->number);
	}
	protected function getNumCharCode()
	{
		$str = join('',range(0,9));
		$str1 = join('',range('a','z'));
		$str2 = $str.$str1.strtoupper($str1);
		return substr(str_shuffle($str2),0,$this->number);
	}

	public function outImage()
	{
		//建立畫布
		$this->createImage();
		//填充背景
		$this->fillback();
		//將驗證碼字符放到畫布上
		$this->drawChar();
		//添加干擾
		$this->drawDisturb();
		//輸出
		$this->show();
	}

	protected function createImage()
	{
		$this->image = imagecreatetruecolor($this->width,$this->heigth);
	}
	protected function fillback()//背景顏色
	{
		imagefill($this->image, 0, 0, $this->lightColor());
	}
	protected function lightColor()//淺色
	{
		return imagecolorallocate($this->image, mt_rand(133,255), mt_rand(133,255), mt_rand(133,255));
	}
	protected function darkColor()//深色
	{
		return imagecolorallocate($this->image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));
	}
	protected function drawChar()//放入驗證碼
	{
		$width = ceil($this->width/$this->number);
		for ($i=0; $i < $this->number; $i++) 
		{ 
			$x = mt_rand($i * $width - 5 , ($i+1) * $width -5);
			$y = mt_rand(0 , $this->heigth -15);
			imagechar($this->image, 5, $x, $y, $this->code[$i], $this->darkColor());
		}
	}
	protected function drawDisturb()//添加干擾像素點
	{
		for ($i=0; $i < 500; $i++) { 
			$x = mt_rand(0 , $this->width);
			$y = mt_rand(0 , $this->heigth);
			imagesetpixel($this->image, $x, $y, $this->darkColor());
		}
	}
	protected function show()
	{
		header('Content-Type:image/png');
		imagepng($this->image);
	}
}
相關文章
相關標籤/搜索