yii自带有验证码,可以直接使用
首先再LoginForm.php中加入额外字段,验证码字段,并加入验证规则
public $verifyCode;
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
['verifyCode', 'captcha', 'captchaAction'=>'/site/captcha'],
];
}
然后再SiteController中
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'backColor' => 0x3c8dbc,//图片底色
'minLength' => 4, // 最小显示字符
'maxLength' => 5, // 最大显示字符
'padding' => 5, // 字符与图片间距
'height' => 33, //图片高度
'width' => 80, //图片宽度
'foreColor' => 0xffffff, //字体颜色
'offset' => 3, //字符间的间距
],
];
}
同时需要修改behaviors,不然验证码不显示
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'captcha', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
在前端页面login.php中
$form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-8">{input}</div><div class="col-lg-4">{image}</div></div>',
])->label(false);