ThinkPHP 3.2.3实现加减乘除图片验证码


Posted in PHP onDecember 05, 2018

ThinkPHP 3.2.3 自带的验证码类位于 /ThinkPHP/Library/Think/Verify.class.php,字体文件位于 /ThinkPHP/Library/Think/Verify/

可以在 Verify.class.php 文件内进行修改,也可以单独写一个类继承自带的验证码类。如果单独写一个继承的类,可以重用父类的属性和方法,但是要注意的是父类中有一些属性和方法是私有(private)的,可以修改这些私有的属性和方法为保护(protected)的,如果不希望修改框架自带的方法的话,也可以在子类中再定义这些属性和方法。

测试的控制器位于 /Application/Home/Controller/TestVerifyController.class.php

测试的试图位于 /Application/Home/View/User/verify.html

自定义的子类位于 /Applicaion/Home/Common/VerifyProcess.class.php 

VerifyProcess.class.php:

<?php
 
namespace Home\Common;
use Think\Verify;
 
class VerifyProcess extends Verify {
 
 private $_image = NULL;  // 验证码图片实例
 private $_color = NULL;  // 验证码字体颜色
 
 public function entryProcess($id = '') {
 // 图片宽(px)
 $this->imageW || $this->imageW = $this->length*$this->fontSize*1.5 +
 $this->length*$this->fontSize/2;
 // 图片高(px)
 $this->imageH || $this->imageH = $this->fontSize * 2.5;
 // 建立一幅 $this->imageW x $this->imageH 的图像
 $this->_image = imagecreate($this->imageW, $this->imageH);
 
 // 设置背景  
 imagecolorallocate($this->_image, $this->bg[0], $this->bg[1], $this->bg[2]);
 
 // 验证码字体随机颜色
 $this->_color = imagecolorallocate($this->_image, mt_rand(1,150), 
 mt_rand(1,150), mt_rand(1,150));
 // 验证码使用随机字体
 $ttfPath = $_SERVER['DOCUMENT_ROOT'].'/ThinkPHP/Library/Think/Verify/' . 
 ($this->useZh ? 'zhttfs' : 'ttfs') . '/';
 
 if(empty($this->fontttf)){
  $dir = dir($ttfPath);
  $ttfs = array();  
  while (false !== ($file = $dir->read())) {
   if($file[0] != '.' && substr($file, -4) == '.ttf') {
    $ttfs[] = $file;
   }
  }
  $dir->close();
  $this->fontttf = $ttfs[array_rand($ttfs)];
 }
 $this->fontttf = $ttfPath . $this->fontttf;
  
 if($this->useImgBg) {
  $this->_background();
 }
  
 if ($this->useNoise) {
  // 绘杂点
  $this->_writeNoise();
 }
 if ($this->useCurve) {
  // 绘干扰线
  $this->_writeCurve();
 }
  
 // 绘验证码
 $codeNX = 0; // 验证码第N个字符的左边距
 
 // 验证码为简单运算
 $a = mt_rand(1,9);
 $b = mt_rand(1,9);
 $operate_array = array('+', '-', '*');
 $key = mt_rand(0, count($operate_array) - 1);
  
 if($operate_array[$key] == '+') { // 加法
  $code = $a.'+'.$b.'=';
  $result = intval($a + $b);
 } elseif($operate_array[$key] == '-') { // 减法
  $code = max($a,$b).'-'.min($a,$b).'=';
  $result = intval(abs($a - $b));
 } else { // 乘法
  $code = $a.'*'.$b.'=';
  $result = intval($a * $b);
 }
 
 $this->length = 4;
 
 for ($i = 0; $i<$this->length; $i++) {
  $codeNX += mt_rand($this->fontSize*1.2, $this->fontSize*1.6);
  imagettftext($this->_image, $this->fontSize, mt_rand(-40, 40), 
  $codeNX, $this->fontSize*1.6, $this->_color, $this->fontttf, $code[$i]);
 }
 
 // 保存验证码
 $key  = $this->authcode($this->seKey);
 $result  = $this->authcode($result);
 $secode  = array();
 $secode['verify_code'] = $result; // 把校验码保存到session
 $secode['verify_time'] = NOW_TIME; // 验证码创建时间
 session($key.$id, $secode);
  
 header('Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate');
 header('Cache-Control: post-check=0, pre-check=0', false);  
 header('Pragma: no-cache');
 header("content-type: image/png");
 
 // 输出图像
 imagepng($this->_image);
 imagedestroy($this->_image);
 }
 
 /**
 * 画杂点
 * 往图片上写不同颜色的字母或数字
 */
 private function _writeNoise() {
  $codeSet = '2345678abcdefhijkmnpqrstuvwxyz';
  for($i = 0; $i < 10; $i++){
   //杂点颜色
   $noiseColor = imagecolorallocate($this->_image, mt_rand(150,225), 
   mt_rand(150,225), mt_rand(150,225));
   for($j = 0; $j < 5; $j++) {
    // 绘杂点
    imagestring($this->_image, 5, mt_rand(-10, $this->imageW), 
   mt_rand(-10, $this->imageH), $codeSet[mt_rand(0, 29)], $noiseColor);
   }
  }
 }
 
 /**
 * 画一条由两条连在一起构成的随机正弦函数曲线作干扰线(你可以改成更帅的曲线函数)
 *  
 *  高中的数学公式咋都忘了涅,写出来
 *  正弦型函数解析式:y=Asin(ωx+φ)+b
 *  各常数值对函数图像的影响:
 *  A:决定峰值(即纵向拉伸压缩的倍数)
 *  b:表示波形在Y轴的位置关系或纵向移动距离(上加下减)
 *  φ:决定波形与X轴位置关系或横向移动距离(左加右减)
 *  ω:决定周期(最小正周期T=2π/?ω?)
 *
 */
 private function _writeCurve() {
 $px = $py = 0;
  
 // 曲线前部分
 $A = mt_rand(1, $this->imageH/2);     // 振幅
 $b = mt_rand(-$this->imageH/4, $this->imageH/4); // Y轴方向偏移量
 $f = mt_rand(-$this->imageH/4, $this->imageH/4); // X轴方向偏移量
 $T = mt_rand($this->imageH, $this->imageW*2); // 周期
 $w = (2* M_PI)/$T;
      
 $px1 = 0; // 曲线横坐标起始位置
 $px2 = mt_rand($this->imageW/2, $this->imageW * 0.8); // 曲线横坐标结束位置
 
 for ($px=$px1; $px<=$px2; $px = $px + 1) {
  if ($w!=0) {
   $py = $A * sin($w*$px + $f)+ $b + $this->imageH/2; 
   // y = Asin(ωx+φ) + b
   $i = (int) ($this->fontSize/5);
   while ($i > 0) {
    imagesetpixel($this->_image, $px + $i , $py + $i, $this->_color); 
    // 这里(while)循环画像素点比imagettftext和imagestring用字体大小一次画出
    (不用这while循环)性能要好很多   
    $i--;
   }
  }
 }
  
 // 曲线后部分
 $A = mt_rand(1, $this->imageH/2);     // 振幅 
 $f = mt_rand(-$this->imageH/4, $this->imageH/4); // X轴方向偏移量
 $T = mt_rand($this->imageH, $this->imageW*2); // 周期
 $w = (2* M_PI)/$T;  
 $b = $py - $A * sin($w*$px + $f) - $this->imageH/2;
 $px1 = $px2;
 $px2 = $this->imageW;
 
 for ($px=$px1; $px<=$px2; $px=$px+ 1) {
  if ($w!=0) {
   $py = $A * sin($w*$px + $f)+ $b + $this->imageH/2; 
   // y = Asin(ωx+φ) + b
   $i = (int) ($this->fontSize/5);
   while ($i > 0) {  
    imagesetpixel($this->_image, $px + $i, $py + $i, $this->_color); 
    $i--;
   }
  }
 }
 }
 
 /* 加密验证码 */
 private function authcode($str){
 $key = substr(md5($this->seKey), 5, 8);
 $str = substr(md5($str), 8, 10);
 return md5($key . $str);
 } 
 
 /**
 * 绘制背景图片
 * 注:如果验证码输出图片比较大,将占用比较多的系统资源
 */
 private function _background() {
  $path = dirname(__FILE__).'/Verify/bgs/';
  $dir = dir($path);
 
  $bgs = array();  
  while (false !== ($file = $dir->read())) {
   if($file[0] != '.' && substr($file, -4) == '.jpg') {
    $bgs[] = $path . $file;
   }
  }
  $dir->close();
 
  $gb = $bgs[array_rand($bgs)];
 
  list($width, $height) = @getimagesize($gb);
  // Resample
  $bgImage = @imagecreatefromjpeg($gb);
  @imagecopyresampled($this->_image, $bgImage, 0, 0, 0, 0, $this->imageW, 
  $this->imageH, $width, $height);
  @imagedestroy($bgImage);
 } 
}

TestVerifyController.class.php:

<?php
namespace Home\Controller;
use Think\Controller;
use Home\Common\VerifyProcess;
 
class TestVerifyController extends Controller {
 
 // 界面
 public function index() {
  $this->display('User/verify');
 }
 
 // 验证
 public function check_verify() {
   
  $verify = new VerifyProcess();
 if(!$verify->check($_POST['verify'])) {
  $this->error('验证码错误');
 }
 }
 
 // 显示验证码
 public function verify() {
   $verify = new VerifyProcess();
   $verify->entryProcess();
 } 
}

verify.html:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
</head>
<body>
 <form action="{:U('Home/TestVerify/check_verify','','')}" method="post">
  <table>
   <tr>
    <td>验证码:</td>
    <td><input type="text" name="verify"></td>
    <td>
     <img id="verify" src="{:U('Home/TestVerify/verify','','')}" 
     style="cursor: pointer;" alt="">
     <a id="refresh" href="javascript:void(0)" rel="external nofollow" >更换验证码</a>
    </td>
   </tr>
   <tr>
    <td colspan="2">
     <input type="submit" value="提交">
    </td>
   </tr>
  </table>
 </form>
</body>
<script>
 $(function(){
 
  $src = $("#verify").attr('src');
 
  $("#refresh").click(function(){
   change_verify();
  }); 
 
  $("#verify").click(function(){
   change_verify();
  });
 
  function change_verify() {
   $('#verify').attr('src', $src + '?' + Math.random());
  }
 });
 
</script>
</html>

效果:

ThinkPHP 3.2.3实现加减乘除图片验证码

也可以点击图片更换验证码,只需要把点击事件换到图片上就行了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木,关注三水点靠木公众号的更多精彩内容。

PHP 相关文章推荐
php实现从ftp服务器上下载文件树到本地电脑的程序
Feb 10 PHP
PHP实现多进程并行操作的详解(可做守护进程)
Jun 18 PHP
浅析PHP 按位与或 (^ 、&amp;)
Jun 21 PHP
PHP中redis的用法深入解析
Feb 20 PHP
通过curl模拟post和get方式提交的表单类
Apr 23 PHP
php实例分享之二维数组排序
May 15 PHP
PHP大批量插入数据库的3种方法和速度对比
Jul 08 PHP
PHP实现的多彩标签效果代码分享
Aug 21 PHP
ECSHOP在PHP5.5及高版本上报错的解决方法
Aug 31 PHP
PHP扩展Memcache分布式部署方案
Dec 06 PHP
Thinkphp5.0自动生成模块及目录的方法详解
Apr 17 PHP
解决windows上php xdebug 无法调试的问题
Feb 19 PHP
php实现算术验证码功能
Dec 05 #PHP
php使用array_chunk函数将一个数组分割成多个数组
Dec 05 #PHP
Yii支持多域名cors原理的实现
Dec 05 #PHP
php判断电子邮件是否正确方法
Dec 04 #PHP
浅谈Laravel核心解读之Console内核
Dec 02 #PHP
Laravel使用scout集成elasticsearch做全文搜索的实现方法
Nov 30 #PHP
用Laravel Sms实现laravel短信验证码的发送的实现
Nov 29 #PHP
You might like
PHP程序员编程注意事项
2008/04/10 PHP
关于mysql字符集设置了character_set_client=binary 在gbk情况下会出现表描述是乱码的情况
2013/01/06 PHP
关于Sphinx创建全文检索的索引介绍
2013/06/25 PHP
PHP网页游戏学习之Xnova(ogame)源码解读(十一)
2014/06/25 PHP
laravel框架 api自定义全局异常处理方法
2019/10/11 PHP
jQuery插件开发全解析
2012/10/10 Javascript
jquery阻止冒泡事件使用模拟事件
2013/09/06 Javascript
JS根据key值获取URL中的参数值及把URL的参数转换成json对象
2015/08/26 Javascript
javascript实现网站加入收藏功能
2015/12/16 Javascript
一个有意思的鼠标点击文字特效jquery代码
2017/09/23 jQuery
详解vuex之store拆分即多模块状态管理(modules)篇
2018/11/13 Javascript
vue获取时间戳转换为日期格式代码实例
2019/04/17 Javascript
微信小程序实现多行文字超出部分省略号显示功能
2019/10/23 Javascript
纯js+css实现在线时钟
2020/08/18 Javascript
python微信跳一跳系列之棋子定位像素遍历
2018/02/26 Python
Django 使用Ajax进行前后台交互的示例讲解
2018/05/28 Python
Python使用爬虫爬取静态网页图片的方法详解
2018/06/05 Python
python使用folium库绘制地图点击框
2018/09/21 Python
python调用外部程序的实操步骤
2019/03/04 Python
自适应线性神经网络Adaline的python实现详解
2019/09/30 Python
pytorch中交叉熵损失(nn.CrossEntropyLoss())的计算过程详解
2020/01/02 Python
解决Pycharm 中遇到Unresolved reference 'sklearn'的问题
2020/07/13 Python
Python数据分析库pandas高级接口dt的使用详解
2020/12/11 Python
selenium学习教程之定位以及切换frame(iframe)
2021/01/04 Python
HTML5在IE10、火狐下中文乱码问题的解决方法
2013/11/18 HTML / CSS
CAT鞋英国官网:坚固耐用的靴子和鞋
2016/10/21 全球购物
德国旅游网站:weg.de
2018/06/03 全球购物
宝拉珍选英国官网:Paula’s Choice英国
2019/05/29 全球购物
排序都有哪几种方法?请列举。用JAVA实现一个快速排序
2014/02/16 面试题
DTD的含义以及作用
2014/01/26 面试题
经济管理专业自荐信
2013/12/30 职场文书
酒店销售经理岗位职责
2014/01/31 职场文书
成人继续教育实施方案
2014/03/01 职场文书
《东方明珠》教学反思
2014/04/20 职场文书
2014年路政工作总结
2014/12/10 职场文书
victoriaMetrics库布隆过滤器初始化及使用详解
2022/04/05 Golang