带你体验封装类的简便快捷
知识点:php基本语法
构造方法,析构方法,魔术方法
<?php
$code=new code();
$code->outImage();
class code{
//验证码个数
protected $number;
protected $codeType;
protected $width;
protected $height;
protected $image;
protected $code;//验证码字符串
public function __construct($number=4,$codeType=2,$width=100,$height=50){
$this->number=$number;
$this->codeType=$codeType;
$this->width=$width;
$this->height=$height;
$this->code=$this->createCode();//生成验证码函数
//echo $this->code;
}
public function __destruct(){
imagedestory($this->image);//图像销毁应该写到析构方法中
}
public function __get($name){//魔术方法
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;
}
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(){
$numStr=join('',range(0,9));
$str=join('',range('a','z'));
$str=$numStr.$str.strtoupper($str);
return substr(str_shuffle($str),0,$this->number);
}
protected function createImage(){
$this->image=imagecreatetruecolor($this->width,$this->height);
}
protected function fillBack(){
imagefill($this->image,0,0,$this->lightColor());
}
protected function lightColor(){
return imagecolorallocate($this->image,mt_rand(130,255),mt_rand(130,255),mt_rand(130,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->height=15);
imagechar($this->image,5,$x,$y,$this->code[$i],$this->darkColor());
}
}
protected function drawDistub(){
for($i=0;$i<150;$i++){
$x=mt_rand(0,$this->width);
$y=mt_rand(0,$this->height);
imagesetpixel($this->image,$x,$y,$this->lightColor());
}
}
protected function show(){
header('Content-Type:image/png');
imagepng($this->image);
}
public function outImage(){
//创建画布,填充背景色,将验证码字符串划到画布中,添加干扰元素,输出并显示
$this->createImage();
$this->fillBack();
$this->drawChar();
$this->drawDistub();
$this->show();
}
}
?>
步骤:生成验证码,画出验证码(创建画布,填充背景色,将验证码字符串划到画布中,添加干扰元素,输出并显示)