PHP简单验证码类


PHP #验证码 #2012-04-30 09:26

用法:

$captcha = new Captcha(array('type'=>0, 'length'=>4));

$m = isset($_GET['m'])?trim($_GET['m']):'';

yige_setcookie($m.'verify', md5(strtoupper($captcha->verify_str)), 0);

$captcha->draw();

效果图:


以下是类代码:

<?php
/* 一个网在线教程 http://yige.org */

class Captcha {
	
	var $verify_str = "";//随机产生的字符
	var $verify_width = 0;//验证图片宽度
	var $verify_height = 22;//验证图片高度
	var $char_width = 12;//字符宽度
	var $type = 0;//字符类型
	var $length = 4;//字符长度
	
	function Captcha($config = array()) {
		if (count($config) > 0) {
			$this->init($config);
		}
		$this->verify_width = $this->length * $this->char_width;
		
		$this->init_verify_str();
	}
	
	function init($config) {
		foreach ($config as $key => $val) {
			if (isset($this->$key)) {
				$this->$key = $val;
			}
		}
	}
	
	function init_verify_str() {
		switch ($this->type) {
	        case 0:
	            $seed = array ('0','1','2','3','4','5','6','7','8','9');
	            break;
	        case 1:
	            $seed = array ('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	            break;
	        default:
	            $seed = array ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        }
        
        shuffle($seed);
    	$verify_arr = array_slice($seed, 0, $this->length);
    	$this->verify_str = implode("", $verify_arr);
	}
	
	function draw() {
		header("Pragma:no-cache");
		header("Cache-control:no-cache");
		header("Content-type: image/png");
		
		$aimg = imagecreate($this->verify_width, $this->verify_height);
		$back = imagecolorallocate($aimg, 251, 254, 255);
		imagefilledrectangle($aimg, 0, 0, $this->verify_width - 1, $this->verify_height - 1, $back);
		//$border = imagecolorallocate($aimg, 133, 153, 193);
		//imagerectangle($aimg, 0, 0, $this->verify_width - 1, $this->verify_height - 1, $border);
		
		for ($i = 0; $i < $this->length; $i++) {
			$words = imagecolorallocate($aimg, rand(20,200), rand(20,200), rand(20,200));
			$wxp = 5+$i*10+rand(1,3);
			imageString($aimg, 5, $wxp, 1+rand(0,3), substr($this->verify_str,$i,1),$words);
		}
		
		$pixcol = imagecolorallocate($aimg, rand(0,255), rand(0,255), rand(0,255));
		for ($i=0; $i<20; $i++) {
			imagesetpixel($aimg,rand(2,$this->verify_width-2),rand(2,$this->verify_height-2),$pixcol);
		}
		
		imagepng($aimg);
		imagedestroy($aimg);
	}
	
}
?>


相关文章

粤ICP备11097351号-1