yii2的验证码

来源:互联网 发布:电脑加密软件 编辑:程序博客网 时间:2024/04/24 06:09

http://www.yiichina.com/tutorial/750



1. 添加验证码第一步:添加模型层代码,名字我就起了个Check

<?php namespace app\models; use Yii; use yii\base\Model;  class Check extends Model {     public $verifyCode;     public function rules()     {         return [             ['verifyCode', 'captcha','message'=>'验证码输入错误了,傻是不是?'],         ];     }

return里面的验证部分采用的内部验证,验证方式是captcha。

public function attributeLabels()    {        return [            'verifyCode' => '请在右面输入验证码  懂不?',        ];    }}?>

第一步就完成了。开始第二步,建一个控制器

<?phpnamespace app\controllers;use Yii;use yii\filters\AccessControl;use yii\web\Controller;use app\models\Check;class PokpetsController extends Controller{public function actions(){        return [            'error' => [                'class' => 'yii\web\ErrorAction',            ],            'captcha' => [                'class' => 'yii\captcha\CaptchaAction',                'maxLength'=>4,                'minLength'=>4,            ],        ];    }


actions里面还可以定义一些验证码的属性,我只定义了长度,还可以定义背景啦什么的。

public function actionNobody(){        $model = new Check();        if ($model->load(Yii::$app->request->post()) && $model->validate()){            return $this->refresh();        }        return $this->render('nobody',[            'model'=>$model,        ]);    }}?>

终于到了最后一步了,添加视图。注意文件名字,我的控制器是Pokpets
so 视图应该在Pokpets下的nobody.php。

<?phpuse yii\helpers\Html;use yii\bootstrap\ActiveForm;use yii\captcha\Captcha;?><div class="site-contact">                <?php $form = ActiveForm::begin(); ?>                    <?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [                        '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(); ?></div>?>//实现刷新页面验证码改变修改vendor/yiisoft/yii2/captcha/CaptchaValidator.php这个文件就可以了,修改的地方见下图:完美解决方法
0 0
原创粉丝点击