当前位置: 移动技术网 > IT编程>开发语言>PHP > ThinkPHP 3.2.3实现加减乘除图片验证码

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

2019年01月07日  | 移动技术网IT编程  | 我要评论

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>  

效果:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网,关注移动技术网公众号的更多精彩内容。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网