yii2的验证码很简单,使用yii2写接口的时候,它自带的验证码需要简单修改一下。
1. 在 根目录的library下创建一个Captcha.php(library是我自己创建的一个公共的包目录)
<?php
namespace app\library;
use \Yii;
use yii\captcha\CaptchaAction;
use yii\helpers\Url;
use yii\web\Response;
class Captcha extends CaptchaAction
{
public function run()
{
//修改刷新方式,只要参数中包含刷新的key,则刷新验证码
if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) {
$code = $this->getVerifyCode(true);
}else{
$code = $this->getVerifyCode();
}
$this->setHttpHeaders();
Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($code);
}
}
2. 调用(比如在IndexController.php)中
public function actionCaptcha()
{
$params = [
'class' => 'app\library\Captcha',
'fixedVerifyCode' => null,
'backColor' => 0x000300,//背景颜色
'maxLength' => 6, //最大显示个数
'minLength' => 5,//最少显示个数
'padding' => 6,//间距
'height' => 40,//高度
'width' => 130, //宽度
'foreColor' => 0xffffff, //字体颜色
'offset' => 5, //设置字符偏移量 有效果
'controller' => $this,
];
echo (\Yii::createObject($params))->run();
}
3. 验证方式
//。。。
$params = [
'class' => 'app\library\Captcha',
'testLimit' => 1,//超过这个错误次数,就刷新验证码
'controller' => $this,
];
$res = (\Yii::createObject($params))->validate($data['code'], true);//第一个参数是前端传过来的验证码,第二个参数是否验证大小写
if(!$res) throw new \Exception("验证码错误");
//。。。