Yii2 验证码 captcha for rest api

前言

用yii2的restful做了一个APP后端,yii2自带速率控制,很爽,但是有的地方又必须用图片验证码,比如登录的时候,要防止暴力破解。yii2是自带图片验证码的,但是封装的太好了,只适用于web。找来找去,packagist.org上也找到了一个比较好的,叫Gregwar/Captcha,但是用了之后,又转念一想,能不能自行封装一下yii2自带的那个图片验证码呢?于是就有了下面的代码

代码实现

更多类属性请访问yii\captcha\CaptchaAction类文档

<?php
namespace app\models\imgcode;

use yii\captcha\CaptchaAction;

class CodeImgGenerate extends CaptchaAction{
   private $verifycode;

   public function __construct(){
        $this->init();
        //更多api请访问yii\captcha\CaptchaAction类文档
        $this->minLength = 4;
        $this->maxLength = 5;
        $this->foreColor = 0x00ff00;
        $this->width = 80;
        $this->height = 45;
   }
   //return image data//返回图片二进制
   public function inline(){
        return $this->renderImage($this->getPhrase());
   }
   //return image code//返回图片验证码
   public function getPhrase(){
        if($this->verifycode){
            return $this->verifycode;
        }else{
            return $this->verifycode = $this->generateVerifyCode();
        }
   }
}
?>

更新2016-11-18:

已经上传到packagist.org了,走你,可以直接composer,方便快捷

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值