PHP创建验证码

<?php
		class ValidationCode{
		private $width;
		private $height;
		private $codeNum;
		private $image;
		private $disturbColorNum;
		private $checkCode;
		
		function __construct($width=80,$height=40,$codeNum=4){
			$this->width=$width;
			$this->height=$height;
			$this->codeNum=$codeNum;
			$this->checkCode=$this->createCheckCode();
			$number=floor($width*$height/15);
			if($number>240-$codeNum){
			$this->disturbColorNum=240-$codeNum;
			}
			else{
			$this->disturbColorNum=$codeNum;
			}
			
		}
		//通过访问该方法向浏览器输出图像
		function showImage(){
			//创建图片背景
			$this->createImage();
			//创建干扰元素
			$this->setDisturbColor();
			//输出文本
			$this->outputText();
			//输出图像
			$this->outputImage();
		}	
		
		//通过调用该方法获取随机创建的验证码字符串
		function getCheckCode(){
			return $this->checkCode;
		}
		//创建背景图片
		private function createImage(){
			//创建图片资源
			$this->image=imagecreatetruecolor($this->width,$this->height);
			//随机获得背景色
			$backColor=imagecolorallocate($this->image,rand(100,255),rand(120,255),rand(120,255));
			//填充背景色
			imagefill($this->image,0,0,$backColor);
			//设置边框颜色
			$border=imagecolorallocate($this->image,0,0,0);
			//画出矩形边框
			imagerectangle($this->image,0,0,$this->width-1,$this->height-1,$border);
		}
		//创建干扰元素
		private function setDisturbColor(){
			//设置像素点
			for($i=0;$i<$this->disturbColorNum;$i++){
			$color=imagecolorallocate($this->image,rand(0,255),rand(0,255),rand(0,255));
			imagesetpixel($this->image,rand(1,$this->width-2),rand(1,$this->height-2),$color);
			}
			//设置干扰线条,设为10条
			for($i=0;$i<10;$i++){
			//颜色设置
			$color=imagecolorallocate($this->image,rand(2,255),rand(2,244),rand(2,244));
			imagearc($this->image,rand(-10,$this->width),rand(-10,$this->height),rand(20,200),rand(30,300),39,34,$color);
			}
		}
		//创建验证字符
		private function createCheckCode(){
			$code="123456789QWERTYUIPLKJHGFDSAZXCVBNM";
			$string='';
			for($i=0;$i<$this->codeNum;$i++){
				$char=$code{rand(0,strlen($code)-1)};
				$string.=$char;
			}
			return $string;
		 
		}	
		//创建输出的字符
		private function outputText(){
			for($i=0;$i<$this->codeNum;$i++){
				$fontcolor=imagecolorallocate($this->image,rand(0,125),rand(1,124),rand(2,125));
				$fontsize=rand(2,5);
				$x=floor($this->width/$this->codeNum)*$i+3;
				$y=rand(0,$this->height-15);
				imagechar($this->image,$fontsize,$x,$y,$this->checkCode{$i},$fontcolor);
			}
		}
		
		private function outputImage(){
		if(imagetypes()&IMG_GIF){
			header("Content-Type:image/gif");
			imagepng($this->image);
		}
		else if(imagetypes()&IMG_JPG){
			header("Content-Type:image/jpeg");
			imagepng($this->image);
		}
		else if(imagetypes()&IMG_PNG){
			header("Content-Type:image/png");
			imagepng($this->image);
		}		
		}
		
		function __destruct(){			
			imagedestroy($this->image);		
			}		
		}

你可能感兴趣的:(PHP创建验证码)