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.MVC的模板标签系统(四)
Sep 05 PHP
在线竞拍系统的PHP实现框架(二)
Oct 09 PHP
php预定义常量
Dec 25 PHP
如何使用“PHP” 彩蛋进行敏感信息获取
Aug 07 PHP
php实现下载限制速度示例分享
Feb 13 PHP
Fatal error: session_start(): Failed to initialize storage module: files问题解决方法
May 04 PHP
Thinkphp多文件上传实现方法
Oct 31 PHP
PHP实现的下载远程图片自定义函数分享
Jan 28 PHP
php+mysqli事务控制实现银行转账实例
Jan 29 PHP
PHP实现文件上传和多文件上传
Dec 24 PHP
PHP文件系统管理(实例讲解)
Sep 19 PHP
laravel 查询数据库获取结果实现判断是否为空
Oct 24 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中函数rand和mt_rand的区别比较
2012/12/26 PHP
PHP中使用循环实现的金字塔图形
2014/11/08 PHP
php数字每三位加逗号的功能函数
2015/10/22 PHP
PHPMailer发送邮件
2016/12/28 PHP
php生成条形码的图片的实例详解
2017/09/13 PHP
PHP判断当前使用的是什么浏览器(推荐)
2019/10/27 PHP
向当前style sheet中插入一个新的style实现方法
2013/04/01 Javascript
JavaScript将数据转换成整数的方法
2014/01/04 Javascript
js获取会话框prompt的返回值的方法
2015/01/10 Javascript
DOM操作和jQuery实现选项移动操作的简单实例
2016/06/07 Javascript
用jQuery向div中添加Html文本内容的简单实现
2016/07/13 Javascript
vue.js实现刷新当前页面的方法教程
2017/07/05 Javascript
Vue.js进行查询操作的实例详解
2017/08/25 Javascript
jquery实现限制textarea输入字数的方法
2017/09/06 jQuery
vue 动态修改a标签的样式的方法
2018/01/18 Javascript
JS字符串和数组如何实现相互转化
2020/07/02 Javascript
nestjs返回给前端数据格式的封装实现
2021/02/22 Javascript
Python实现的径向基(RBF)神经网络示例
2018/02/06 Python
Python实现的FTP通信客户端与服务器端功能示例
2018/03/28 Python
python3实现163邮箱SMTP发送邮件
2018/05/22 Python
Windows下安装Scrapy
2018/10/17 Python
Python中py文件转换成exe可执行文件的方法
2019/06/14 Python
Python实现K折交叉验证法的方法步骤
2019/07/11 Python
不到20行实现Python代码即可制作精美证件照
2020/04/24 Python
python实现五子棋程序
2020/04/24 Python
Python控制鼠标键盘代码实例
2020/12/08 Python
CSS3 3D立方体效果示例-transform也不过如此
2016/12/05 HTML / CSS
Html5大文件断点续传实现方法
2015/12/05 HTML / CSS
印尼太阳百货公司网站:Matahari
2018/02/04 全球购物
Gerry Weber德国官网:优质女性时装,德国最大的时装公司之一
2019/11/02 全球购物
我的求职计划书
2014/01/10 职场文书
幼儿园教师工作感言
2014/02/15 职场文书
元旦文艺汇演主持词
2014/03/26 职场文书
《埃及的金字塔》教学反思
2014/04/07 职场文书
大学生个人先进事迹材料范文
2014/05/03 职场文书
Python语言中的数据类型-序列
2022/02/24 Python