Yii2 扩展图形验证码,修复点击图形验证码无法更新问题

应用场景

在基于Yii2开发发送短信验证功能时,申请短信模板一直没通过,反馈结果“验证码过于简单”,但Yii2 生成的验证是没有干扰的。所以基于Yii2 验证码进行扩展。Yii2 图形验证码还存在“点击图形验证码时无法更新”问题。

生成验证码

视图代码

在需要生成图形验证码视图,添加以下代码

'captchaimg','captchaAction'=>'register/captcha','imageOptions'=>['id'=>'captchaimg', 'title'=>'换一个', 'alt'=>'换一个', 'style'=>'cursor:pointer;margin-left:25px;'],'template'=>'{image}']);?>

模型代码

在需要生成图形验证码模型,添加以下代码

public function rules(){
return [

    //验证码    ['verifyCode', 'captcha','captchaAction'=>'register/captcha','message'=>'图片验证码不正确!'],]

}

控制器代码

在需要生成图形验证码控制器,添加以下代码

/

  • [actions 验证码]

  • @author 邱先生

  • @copyright 烟火里的尘埃

  • @version [V1.0版本]

  • @date 2016-07-08

  • @return [type] [description]
    */
    public function actions() {
    return [
    'captcha' => [
    'class' => 'yii\captcha\CaptchaAction',
    'height' => 80,
    'width' => 200,
    'minLength' => 4,
    'maxLength' => 4,
    'foreColor' => 0x2eaeff,
    'offset' =>25,
    'disturbCharCount' =>2,//干扰字符数量
    'transparent' => false,

        ],];

    }

增加干扰线

不分析源码,找到vendor\yiisoft\yii2\captcha\CaptchaAction.php 覆盖即可

  • @since 2.0
    */
    class CaptchaAction extends Action
    {
    /

    • The name of the GET parameter indicating whether the CAPTCHA image should be regenerated.
      */
      const REFRESH_GET_VAR = 'refresh';

    /

    • @var integer how many times should the same CAPTCHA be displayed. Defaults to 3.
    • A value less than or equal to 0 means the test is unlimited (available since version 1.1.2).
      */
      public $testLimit = 3;
      /
    • @var integer the width of the generated CAPTCHA image. Defaults to 120.
      */
      public $width = 120;
      /
    • @var integer the height of the generated CAPTCHA image. Defaults to 50.
      */
      public $height = 50;
      /
    • @var integer padding around the text. Defaults to 2.
      */
      public $padding = 2;
      /
    • @var integer the background color. For example, 0x55FF00.
    • Defaults to 0xFFFFFF, meaning white color.
      */
      public $backColor = 0xFFFFFF;
      /
    • @var integer the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color).
      */
      public $foreColor = 0x2040A0;
      /
    • @var boolean whether to use transparent background. Defaults to false.
      */
      public $transparent = false;
      /
    • @var integer the minimum length for randomly generated word. Defaults to 6.
      */
      public $minLength = 6;
      /
    • @var integer the maximum length for randomly generated word. Defaults to 7.
      */
      public $maxLength = 7;
      /
    • @var integer the offset between characters. Defaults to -2. You can adjust this property
    • in order to decrease or increase the readability of the captcha.
      */
      public $offset = -2;
      /
    • @var string the TrueType font file. This can be either a file path or path alias.
      */
      public $fontFile = '@yii/captcha/SpicyRice.ttf';
      /
    • @var string the fixed verification code. When this property is set,
    • [[getVerifyCode()]] will always return the value of this property.
    • This is mainly used in automated tests where we want to be able to reproduce
    • the same verification code each time we run the tests.
    • If not set, it means the verification code will be randomly generated.
      */
      public $fixedVerifyCode;
      /
    • @var string the rendering library to use. Currently supported only 'gd' and 'imagick'.
    • If not set, library will be determined automatically.
    • @since 2.0.7
      */
      public $imageLibrary;

    /

    • [$disturbCharCount 干扰字符数量]
    • @var [type]
      */
      public $disturbCharCount=2;
      /
    • Initializes the action.
    • @throws InvalidConfigException if the font file does not exist.
      */
      public function init()
      {
      $this->fontFile = Yii::getAlias($this->fontFile);
      if (!is_file($this->fontFile)) {
      throw new InvalidConfigException("The font file does not exist: {$this->fontFile}");
      }
      }

    /

    • Runs the action.
      */
      public function run()
      {
      if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
      // AJAX request for regenerating code
      $code = $this->getVerifyCode(true);
      Yii::$app->response->format = Response::FORMAT_JSON;
      return [
      'hash1' => $this->generateValidationHash($code),
      'hash2' => $this->generateValidationHash(strtolower($code)),
      // we add a random 'v' parameter so that FireFox can refresh the image
      // when src attribute of image tag is changed
      'url' => Url::to([$this->id, 'v' => uniqid()]),
      ];
      } else {
      $this->setHttpHeaders();
      Yii::$app->response->format = Response::FORMAT_RAW;
      return $this->renderImage($this->getVerifyCode(true));
      }
      }

    /

    • Generates a hash code that can be used for client side validation.

    • @param string $code the CAPTCHA code

    • @return string a hash code generated from the CAPTCHA code
      */
      public function generateValidationHash($code)
      {
      for ($h = 0, $i = strlen($code) - 1; $i >= 0; --$i) {
      $h += ord($code[$i]);
      }

      return $h;
      }

    /

    • Gets the verification code.

    • @param boolean $regenerate whether the verification code should be regenerated.

    • @return string the verification code.
      */
      public function getVerifyCode($regenerate = false)
      {
      if ($this->fixedVerifyCode !== null) {
      return $this->fixedVerifyCode;
      }

      $session = Yii::$app->getSession();
      $session->open();
      $name = $this->getSessionKey();
      if ($session[$name] === null || $regenerate) {
      $session[$name] = $this->generateVerifyCode();
      $session[$name . 'count'] = 1;
      }

      return $session[$name];
      }

    /

    • Validates the input to see if it matches the generated code.

    • @param string $input user input

    • @param boolean $caseSensitive whether the comparison should be case-sensitive

    • @return boolean whether the input is valid
      */
      public function validate($input, $caseSensitive)
      {
      $code = $this->getVerifyCode();
      $valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0;
      $session = Yii::$app->getSession();
      $session->open();
      $name = $this->getSessionKey() . 'count';
      $session[$name] = $session[$name] + 1;
      if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) {
      $this->getVerifyCode(true);
      }

      return $valid;
      }

    /

    • Generates a new verification code.

    • @return string the generated verification code
      */
      protected function generateVerifyCode()
      {
      if ($this->minLength > $this->maxLength) {
      $this->maxLength = $this->minLength;
      }
      if ($this->minLength minLength = 3;
      }
      if ($this->maxLength > 20) {
      $this->maxLength = 20;
      }
      $length = mt_rand($this->minLength, $this->maxLength);

      $letters = '123456789bcdfghjklmnpqrstvwxyz';
      $vowels = 'aeiou';
      $code = '';
      for ($i = 0; $i 2 || !($i % 2) && mt_rand(0, 10) > 9) {
      $code .= $vowels[mt_rand(0, 4)];
      } else {
      $code .= $letters[mt_rand(0, 20)];
      }
      }

      return $code;
      }

    /

    • Returns the session variable name used to store verification code.
    • @return string the session variable name
      */
      protected function getSessionKey()
      {
      return '__captcha/' . $this->getUniqueId();
      }

    /

    • Renders the CAPTCHA image.
    • @param string $code the verification code
    • @return string image contents
    • @throws InvalidConfigException if imageLibrary is not supported
      */
      protected function renderImage($code)
      {
      if (isset($this->imageLibrary)) {
      $imageLibrary = $this->imageLibrary;
      } else {
      $imageLibrary = Captcha::checkRequirements();
      }
      if ($imageLibrary === 'gd') {
      return $this->renderImageByGD($code);
      } elseif ($imageLibrary === 'imagick') {
      return $this->renderImageByImagick($code);
      } else {
      throw new InvalidConfigException("Defined library '{$imageLibrary}' is not supported");
      }
      }

    /

    • Renders the CAPTCHA image based on the code using GD library.

    • @param string $code the verification code

    • @return string image contents in PNG format.
      */
      protected function renderImageByGD($code)
      {
      $image = imagecreatetruecolor($this->width, $this->height);

      $backColor = imagecolorallocate(
      $image,
      (int) ($this->backColor % 0x1000000 / 0x10000),
      (int) ($this->backColor % 0x10000 / 0x100),
      $this->backColor % 0x100
      );
      imagefilledrectangle($image, 0, 0, $this->width, $this->height, $backColor);
      imagecolordeallocate($image, $backColor);

      if ($this->transparent) {
      imagecolortransparent($image, $backColor);
      }

      $foreColor = imagecolorallocate(
      $image,
      (int) ($this->foreColor % 0x1000000 / 0x10000),
      (int) ($this->foreColor % 0x10000 / 0x100),
      $this->foreColor % 0x100
      );

      $length = strlen($code);
      $box = imagettfbbox(30, 0, $this->fontFile, $code);
      $w = $box[4] - $box[0] + $this->offset ($length - 1);
      $h = $box[1] - $box[5];
      $scale = min(($this->width - $this->padding
      2) / $w, ($this->height - $this->padding 2) / $h);
      $x = 20;
      $y = round($this->height
      27 / 40);
      for ($i = 0; $i fontFile, $letter);
      $x = $box[2] + $this->offset;
      }

      ob_start();
      //画干扰点
      $this->_writeNoise($image);
      //画干扰线
      $this->_writeCurve($image);
      $this->_writeCurve($image);
      // $this->_writeCurve($image);
      $this->_writeCurve($image);
      imagepng($image);
      imagedestroy($image);
      return ob_get_clean();
      }

    /

    • 画杂点

    • 往图片上写不同颜色的字母或数字
      */
      private function _writeNoise($image) {
      $codeSet = '2345678abcdefhijkmnpqrstuvwxyz';
      for($i = 0; $i disturbCharCount; $i++){
      //杂点颜色
      $noiseColor = imagecolorallocate($image, mt_rand(150,225), mt_rand(150,225), mt_rand(150,225));
      for($j = 0; $j width), mt_rand(-10, $this->height), $codeSet[mt_rand(0, 29)], $noiseColor);
      }
      }
      }
      /

    • 画一条由两条连在一起构成的随机正弦函数曲线作干扰线(你可以改成更帅的曲线函数)

    • 高中的数学公式咋都忘了涅,写出来

    • 正弦型函数解析式:y=Asin(ωx+φ)+b

    • 各常数值对函数图像的影响:

    • A:决定峰值(即纵向拉伸压缩的倍数)

    • b:表示波形在Y轴的位置关系或纵向移动距离(上加下减)

    • φ:决定波形与X轴位置关系或横向移动距离(左加右减)

    • ω:决定周期(最小正周期T=2π/∣ω∣)

    • */
      // 验证码字体随机颜色
      // $this->_color = imagecolorallocate($this->_image, mt_rand(1,150), mt_rand(1,150), mt_rand(1,150));
      private function _writeCurve($image) {
      $px = $py = 0;

      // 曲线前部分
      $A = mt_rand(1, $this->height/2); // 振幅
      $b = mt_rand(-$this->height/4, $this->height/4); // Y轴方向偏移量
      $f = mt_rand(-$this->height/4, $this->height/4); // X轴方向偏移量
      $T = mt_rand($this->height, $this->width2); // 周期
      $w = (2
      M_PI)/$T;

      $px1 = 0; // 曲线横坐标起始位置
      $px2 = mt_rand($this->width/2, $this->width * 0.8); // 曲线横坐标结束位置

      for ($px=$px1; $pxheight/2; // y = Asin(ωx+φ) + b
      $i = (int) (15/5);
      while ($i > 0) {
      imagesetpixel($image, $px + $i , $py + $i, imagecolorallocate($image, mt_rand(1,150), mt_rand(1,150), mt_rand(1,150))); // 这里(while)循环画像素点比imagettftext和imagestring用字体大小一次画出(不用这while循环)性能要好很多
      $i--;
      }
      }
      }

      // 曲线后部分
      $A = mt_rand(1, $this->height/2); // 振幅
      $f = mt_rand(-$this->height/4, $this->height/4); // X轴方向偏移量
      $T = mt_rand($this->height, $this->width2); // 周期
      $w = (2
      M_PI)/$T;
      $b = $py - $A sin($w$px + $f) - $this->height/2;
      $px1 = $px2;
      $px2 = $this->width;

      for ($px=$px1; $pxheight/2; // y = Asin(ωx+φ) + b
      $i = (int) (15/5);
      while ($i > 0) {
      imagesetpixel($image, $px + $i, $py + $i, imagecolorallocate($image, mt_rand(1,150), mt_rand(1,150), mt_rand(1,150)));
      $i--;
      }
      }
      }
      }

    /

    • Renders the CAPTCHA image based on the code using ImageMagick library.

    • @param string $code the verification code

    • @return string image contents in PNG format.
      */
      protected function renderImageByImagick($code)
      {
      $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('# ' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
      $foreColor = new \ImagickPixel('# ' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));

      $image = new \Imagick();
      $image->newImage($this->width, $this->height, $backColor);

      $draw = new \ImagickDraw();
      $draw->setFont($this->fontFile);
      $draw->setFontSize(30);
      $fontMetrics = $image->queryFontMetrics($draw, $code);

      $length = strlen($code);
      $w = (int) ($fontMetrics['textWidth']) - 8 + $this->offset ($length - 1);
      $h = (int) ($fontMetrics['textHeight']) - 8;
      $scale = min(($this->width - $this->padding
      2) / $w, ($this->height - $this->padding 2) / $h);
      $x = 10;
      $y = round($this->height
      27 / 40);
      for ($i = 0; $i setFont($this->fontFile);
      $draw->setFontSize((int) (rand(26, 32) $scale 0.8));
      $draw->setFillColor($foreColor);
      $image->annotateImage($draw, $x, $y, rand(-10, 10), $code[$i]);
      $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
      $x += (int) ($fontMetrics['textWidth']) + $this->offset;
      }

      $image->setImageFormat('png');
      return $image->getImageBlob();
      }

    /

    • Sets the HTTP headers needed by image response.
      */
      protected function setHttpHeaders()
      {
      Yii::$app->getResponse()->getHeaders()
      ->set('Pragma', 'public')
      ->set('Expires', '0')
      ->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
      ->set('Content-Transfer-Encoding', 'binary')
      ->set('Content-type', 'image/png');
      }
      }

修复点击图片验证码无法更新(后续更新)

关键字:yii2

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部