phpGrace 封装了 verifyCode 工具类用于生成图片验证码,并可以使用 session 记录验证码数据。
use grace\tool\verifyCode;
__construct($width = 88, $height = 30, $totalChars = 4, $numbers = 1, $fontFamily = null) 参数 : 1. 图片验证码宽度,可选参数,默认 88; 2. 图片验证码高度,可选参数,默认 30; 3. 图片验证码字符总数,可选参数,默认 4; 4. 图片验证码字符中数字字符的数量,可选参数,默认 1; 5. 图片验证码使用的字体文件,可选参数,默认 FiraCode.ttf; 如果需要使用自定义字体,请复制字体文件到 : /站点目录/***.ttf , 实参示例 :PG_APP_ROOT.PG_WEBSITE_NAME.PG_DS.'FiraCode.ttf',其他目录同理。
public $bgColor = array(255,255,255); // 背景颜色 public $codeColor = array(0, 0, 0); // 验证码颜色 public $fontSize = 16; // 验证码字符大小 public $securityCode; // 验证码内容 public $charNoiseNumber = 10; // 干扰字符数量, 0 代表关闭 public $lineNoiseNumber = 5; // 干扰线数量,0 代表关闭 public $saveWithSession = true; // 是否利用session保存验证码 public $sessionName = 'pgVCode'; // 验证码在Session中储存的名称
# 控制器代码
<?php namespace grace\controller; use grace\grace; use grace\tool\verifyCode; use grace\tool\session; class index extends grace{ public function index() { // 展示视图 } // 验证绘制控制器 public function draw(){ $verifyCode = new verifyCode(88, 32, 5, 1, PG_APP_ROOT.PG_WEBSITE_NAME.PG_DS.'FiraCode.ttf'); /* $verifyCode->bgColor = array(255, 0, 0); //验证码背景颜色 $verifyCode->codeColor = array(0, 255, 0); //验证码文本颜色 $verifyCode->sessionName = 'yourname'; //保存验证码的 session 名称 */ /* 生成已知字符的验证码,不需要 session 记录 $verifyCode->securityCode = 'HG0C81'; $verifyCode->saveWithSession = false; */ $verifyCode->draw(); } // 获取验证码 // 先访问验证码页面 http://localhost // 再访问 http://localhost/index/getVCode获取session中验证码信息 public function getVCode(session $session){ echo $this->session->get('pgVCode'); } }
# 视图代码 ( 含点击切换演示 )
<html> <head> <title></title> </head> <body> <form action="" method="post"> 验证码 : <br /> <input type="text" name="yzm" /><img src="/index/draw" onclick="changeVcode(this);" /><br /> <input type="submit" id="" value="提交" /> </form> <script type="text/javascript"> //点击更换验证码 function changeVcode(vcodeImg){ vcodeImg.setAttribute('src', '/index/draw/' + Math.random()); } </script> </body> </html>