说明
- Yii2框架的官方文档对于验证码的使用涉及的篇幅很少,然而验证码在开发中其实使用得非常多,以下是通过查阅资料,摸索出的方案
- 解决了验证码不能刷新的问题
使用步骤
1. 定义验证码action
- 和error一样,验证码需定义在actions方法中
- 通常为了方便,可以直接将它定义在SiteController中,如果想定义在控制器也可以,只是调用时一定要指明是哪个控制中
以SiteController为例
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
class SiteController extends Controller
{
/**
* @var string $layout 指定使用error布局
*/
public $layout = 'error';
/**
* 定义captcah验证码,和默认错误展示页面
*/
public function actions()
{
return [
//验证码action
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'backColor'=>0x000000,//背景颜色
'maxLengt