创建干扰线条
//创建干扰线条(默认四条)
public function createLines(){
for ($i=0; $i img,mt_rand(0,155),mt_rand(0,155),mt_rand(0,155)); //使用浅色
imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
}
用到的相关函数:
imageline:画一条线段
创建干扰点
//创建干扰点 (默认一百个点)
public function createPiex(){
for ($i=0; $i img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagesetpixel($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
}
使用的相关函数:
imagesetpixel:画一个单一像素
对外输出图像:
public function show()
{
$this->createImage();
$this->createCode();
if ($this->lineFlag) { //是否创建干扰线条
$this->createLines();
}
if ($this->piexFlag) { //是否创建干扰点
$this->createPiex();
}
header('Content-type:image/png'); //请求页面的内容是png格式的图像
imagepng($this->img); //以png格式输出图像
imagedestroy($this->img); //清除图像资源,释放内存
}
用到的相关函数:
imagepng:以 PNG 格式将图像输出到浏览器或文件
imagedestroy:销毁一图像
对外提供验证码:
public function getCode(){
return $this->code;
}
完整代码如下:
string = 'qwertyupmkjnhbgvfcdsxa123456789';
$this->codeNum = $codeNum;
$this->height = $height;
$this->width = $width;
$this->lineFlag = $lineFlag;
$this->piexFlag = $piexFlag;
$this->font = dirname(__FILE__).'/fonts/consola.ttf';
$this->fontSize = $fontSize;
}
public function createImage(){
$this->($this->width, $this->height);
imagecolorallocate($this->img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
}
public function createCode(){
$strlen = strlen($this->string)-1;
for ($i=0; $i codeNum; $i++) {
$this->code .= $this->string[mt_rand(0,$strlen)];
}
$_SESSION['code'] = $this->code;
$diff = $this->width/$this->codeNum;
for ($i=0; $i codeNum; $i++) {
$txtColor = imagecolorallocate($this->img,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
imagettftext($this->img, $this->fontSize, mt_rand(-30,30), $diff*$i+mt_rand(3,8), mt_rand(20,$this->height-10), $txtColor, $this->font, $this->code[$i]);
}
}
public function createLines(){
for ($i=0; $i img,mt_rand(0,155),mt_rand(0,155),mt_rand(0,155));
imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
}
public function createPiexs(){
for ($i=0; $i img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagesetpixel($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
}
public function show()
{
$this->createImage();
$this->createCode();
if ($this->lineFlag) {
$this->createLines();
}
if ($this->piexFlag) {
$this->createPiexs();
}
header('Content-type:image/png');
imagepng($this->img);
imagedestroy($this->img);
}
public function getCode(){
return $this->code;
}
}
以上就是验证码类的全部代码。看起来确实挺简单的,不过用的图像处理函数比较多,上面相关的函数我也做了必要的链接和用途说明。这些函数也不用死记硬背,遇到不清楚的,随时查阅 PHP 官方文档,最重要的是还有中文文档。
2.2 使用验证码
既然已经封装完毕,那就可以开始使用了。这里为了方便,直接在 Captcha 类的下方调用该类:
session_start(); //开启session
$captcha = new Captcha(); //实例化验证码类(可自定义参数)
$captcha->show(); //调用输出
三、前端展示
后端已经准备好了验证码,前端界面就可以展示了,修改 index.php 中的注册与登陆表单的验证码部分: