可直接运行查看效果,代码附了大量备注,如有疑问可留言交流。
<?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);
}
}