1.基本概念
1.1定义验证码action
public function actions()
{
return [
//验证码action
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'test' : null,
'backColor'=>0x000000,//背景颜色
'maxLength' => 5, //最大显示个数
'minLength' => 4,//最少显示个数
'padding' => 3,//间距
'height'=>34,//高度
'width' => 90, //宽度
'foreColor'=>0xffffff, //字体颜色
'offset'=>4 //设置字符偏移量 有效果
],
];
}
1.2视图中输出验证码图片
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'verifyCode')->widget('yii\captcha\Captcha', [
'captchaAction'=>'test/captcha',
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('验证一下', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
1.3模型层验证
public function rules()
{
return [
[['name', 'email', 'subject', 'body'], 'required'],
['email', 'email'],
['verifyCode', 'captcha']
]
}
1.4网页刷新验证码不刷新问题
<?php
namespace frontend\components;
use yii\web\Response;
class CaptchaAction extends \yii\captcha\CaptchaAction {
public function run() {
$this->setHttpHeaders();
\Yii::$app->response->format = Response::FORMAT_RAW;
return $this->renderImage($this->getVerifyCode(true));
}
}
?>
2.使用
2.1控制器
<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
/**
* Site controller
*/
class TestController extends Controller {
public function actions() {
return [
//验证码action
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'test' : null,
'backColor'=>0x000000,//背景颜色
'maxLength' => 5, //最大显示个数
'minLength' => 2,//最少显示个数
'padding' => 3,//间距
'height'=>34,//高度
'width' => 90, //宽度
'foreColor'=>0xffffff, //字体颜色
'offset'=>4 //设置字符偏移量 有效果
],
];
}
public function actionReg() {
$model = new \backend\models\RegForm();
return $this->render('reg',['model'=>$model]);
}
}
2.2模型
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
class RegForm extends Model {
public $verifyCode;
public function rules() {
return [
['verifyCode', 'captcha','captchaAction'=>'test/captcha'] //这里的test/captcha表示那个控制器下使用就写相应的控制器信息,这里是在text/reg中使用。验证码调用的是captcha
];
}
}
2.3视图
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'verifyCode')->widget('yii\captcha\Captcha', [
'captchaAction'=>'test/captcha',
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('验证一下', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>