PHP封装的验证码工具类定义与用法示例封装的验证码工具类定义与用法示例
本文实例讲述了PHP封装的验证码工具类定义与用法。分享给大家供大家参考,具体如下:
下面分享的是我自己封装的验证码工具类,在平时的项目中会比较经常用到的工具类,目前封装的这个工具类简易版的,如果
有需要的伙伴可以拿去用,当然我建议用之前在配置文件里增加一些选项信息
//验证码宽度
private $width;
//验证码高度
private $height;
//验证的个数
private $length;
//干扰点个数
private $dots;
//干扰点的类型
private $type;
//干扰线个数
private $lines;
//文字
private $font;
方便在项目中对验证码的要求进行更改,以方便项目逻辑的需求,而且验证码所选用的字体需要和验证码工具类放在同一目录
下,否则就要在配置文件中修改字体的路径才能实现验证码的显示
<?php
//创建验证码工具类
class captcha {
//验证码的各种参数
//验证码宽度
private $width;
//验证码高度
private $height;
//验证的个数
private $length;
//干扰点个数
private $dots;
//干扰点的类型
private $type;
//干扰线个数
private $lines;
//文字
private $font;
//验证码属性的构造方法
public function __construct($arr = array ()) {
//将属性赋值
$this->width = isset ($arr['width']) ? trim($arr['width']) : '270';
$this->height = isset ($arr['height']) ? trim($arr['height']) : '30';
$this->length = isset ($arr['length']) ? trim($arr['length']) : '4';
$this->dots = isset ($arr['dots']) ? trim($arr['dots']) : '81';
$this->type = isset ($arr['type']) ? trim($arr['type']) : '*';
$this->lines = isset ($arr['lines']) ? trim($arr['lines']) : '5';
$this->font = isset ($arr['font']) ? trim($arr['font']) : './cambriab.ttf';
}
//创建验证码的方法
public function captcha() {
//创建画布
$img = imagecreatetruecolor($this->width, $this->height);
//填充颜色
//颜色资源
$color = imagecolorallocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
//填充背景
imagefill($img, 0, 0, $color);
//添加干扰点
for ($i = 0; $i < $this->dots; $i++) {
//颜色资源
$dots_color = imagecolorallocate($img, mt_rand(150, 200), mt_rand(150, 200), mt_rand(150, 200));
//插入干扰点
imagestring($img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->height), $this->type, $dots_color);
}
//添加干扰线
for ($i = 0; $i < $this->lines; $i++) {
//颜色资源
$line_color = imagecolorallocate($img, mt_rand(150, 200), mt_rand(150, 200), mt_rand(150, 200));
//插入干扰线
imageline($img, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $line_color);
}
评论0
最新资源