yii2自带验证码功能,配置一下就好了,这篇文章以登录页面为例,登录界面加入验证码可以防止暴力破解登录密码。
主要修改三个文件:LoginForm.php,siteController.php,login.php,
三个文件里面都引入下面类
use yii\captcha\CaptchaAction;
use yii\captcha\Captcha;
1.修改模型LoginForm类:
public $verifyCode;//给model增加一个属性
public function rules()
{
return [
// username and password are both required
[['username', 'password','verifyCode'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
['verifyCode', 'captcha'],
];
}
public function attributeLabels()
{
return [
// 'verifyCode' => 'Verification Code',
'username' => '用户名',
'password'=>'密码',
'verifyCode' => '验证码',
];
}
2.修改SiteController.php
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup','login'],
'rules' => [
[
'actions' => ['signup','login','captcha'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* {@inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
/*'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],*/
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
'backColor'=>0x000000,//背景颜色
'maxLength' => 6, //最大显示个数
'minLength' => 5,//最少显示个数
'padding' => 5,//间距
'height'=>40,//高度
'width' => 130, //宽度
'foreColor'=>0xffffff, //字体颜色
'offset'=>4, //设置字符偏移量 有效果
//'controller'=>'login', //拥有这个动作的controller
],
];
}
3.修改view里的login.php
use yii\captcha\Captcha;
<?= $form->field($model, 'verifyCode')->widget(Captcha::className()) ?>
搞定!注册页面加入验证码可以防止恶意注册,原理一样,有兴趣的读者可以自行搞定!