php简易验证码类

<?php
/**
 +----------------------------------------------------------
 * 兄 弟 你 该 努 力 了!- 西 木
 +----------------------------------------------------------
 * 用 途		验证码类($_SESSION['checkstr'])
 +----------------------------------------------------------
 * 文 件 名  checkimg.class.php
 +----------------------------------------------------------
 * 时 间 2011-1-21
 +----------------------------------------------------------
 */
class checkimg{
	/**
	 * 当前验证码
	 */
	public $randstr="";												//验证码
	/**
	 * 验证码长度
	 */
	private $randlang=5;											//验证码长度
	/**
	 * 图片信息:jpg,50,20
	 */
	public $imginfo='jpg,50,16';									//图片尺寸:格式,宽,高

	/**
	 * 背景颜色:255,12,45
	 */
	public $bgcolor='255,255,255';								//背景颜色
	/**
	 * 文字颜色:255,12,45
	 */
	public $textcolor='255,0,0';									//文字颜色

	public function __construct(){								//构造函数

		!isset($_SESSION) && session_start();						//开启session

		$this->createrand();
	}
	/**
	 * 设置验证码长度
	 */
	public function setrandstr($lang){

		$this->randlang=$lang;

		$this->createrand();
	}
	/**
	 * 产生验证码
	 * 0-9=>0-9;10-35=>a-z;35-61=>A-Z
	 * @access public
	 * @param int $start		//随机开始位置
	 * @param int $end			//随机结束位置
	 */
	public function createrand($start=0,$end=61){					//创建随机数

		$this->randstr='';											//初始化

		$_array=array_merge(range(0,9),range(a,z),range(A,Z));		//10-35=>a-z;35-61=>A-Z

		for($i=0;$i<$this->randlang;$i++){

			$this->randstr=$this->randstr.$_array[rand(0,36)];		//得到验证码
		}

		$_SESSION['checkstr']	=strtolower($this->randstr);					//写入session
	}
	/**
	 * 绘画
	 */
	public function createimg(){

		list($img_type,$img_wight,$img_height)=explode(',',$this->imginfo);

		$image=imagecreatetruecolor($img_wight,$img_height);		//创建真彩色图片

		list($bg_r,$bg_g,$bg_b)=explode(',',$this->bgcolor);

		$bgcolor=imagecolorallocate($image,$bg_r,$bg_g,$bg_b);		//背景颜色

		imagefill($image,0,0,$bgcolor);								//填充背景

		list($txt_r,$txt_g,$txt_b)=explode(',',$this->textcolor);

		$textcolor=imagecolorallocate($image,$txt_r,$txt_g,$txt_b);	//字体颜色

		imagestring($image,5,0,0,$this->randstr,$textcolor);		//绘画文字

		switch($img_type){											//选择图片格式并输出

			case 'jpg':

				header("Content-type: image/jpeg");

		    	imagejpeg($image);	break;

			case 'png':

				header("Content-type: image/png");

		     	imagepng($image);	break;

			case 'gif':

				header("Content-type: image/gif");

		     	imagegif($image);	break;

		    default:

				header("Content-type: image/jpeg");

		    	imagejpeg($image);	break;
		}

		imagedestroy($image);										//销毁图片

	}
}

posted on 2011-01-21 15:16  justup  阅读(234)  评论(0)    收藏  举报

导航