您的位置:首页 > 编程语言 > PHP开发

Yii2 验证码 captcha for rest api

2016-11-05 16:49 615 查看

前言

用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,方便快捷
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  yii