您现在的位置是:网站首页>>PHP>>Yii

Yii验证码生成与验证

发布时间:2018-08-17 16:12:12作者:wangjian浏览量:440点赞量:1

    一:新建一个验证码model用于验证验证码的对错

    <?php
    /**
     * Created by PhpStorm.
     * User: wj
     * Date: 2018/8/16
     * Time: 13:53
     */
     namespace app\models;
     use Yii;
     use yii\base\Model;
     class Check extends Model
     {
         public $verifyCode;
         public function rules()
         {
             return [
                 ['verifyCode', 'captcha', 'message' => '验证码输入错误了!','captchaAction' => 'check/captcha'],  #在使用ajax方式使用验证码时使用'captchaAction' => 'check/captcha',否则去除
             ];
         }
         public function attributeLabels()
         {
             return [
                 'verifyCode' => '请输入验证码?',
             ];
         }
     }


    二:在控制器中:

    <?php
    /**
     * Created by PhpStorm.
     * User: wj
     * Date: 2018/8/16
     * Time: 14:03
     */
    namespace app\controllers;
    use Yii;
    use yii\filters\AccessControl;
    use yii\filters\VerbFilter;
    use yii\web\Controller;
    use app\models\Check;
    class CheckController extends Controller
    {
    //    public $layout = false;
        public $enableCsrfValidation = false;
        public function actions()
        {
            return [
                'error' => [
                    'class' => 'yii\web\ErrorAction',
                ],
                'captcha' => [
                    'class' => 'yii\captcha\CaptchaAction',
                    'maxLength' => 5,//最大长度
                    'minLength' => 4,//最小长度
                    'foreColor'=> 0xBF102B,//验证码颜色
                    'backColor'=> 0xFFFFFF,//背景颜色
                    'padding' => 5,//间距
                    'height' => 40,//高度
                    'width' => 130, //宽度
                    'offset' => 4, //设置字符偏移量 有效果
                ],
            ];
        }
        public function actionCheck(){
            $model = new Check();
            if ($model->load(Yii::$app->request->post()) && $model->validate()){
                return $this->refresh();
            }
            return $this->render('check',[
                'model'=>$model,
            ]);
        }
    }

    三:在视图中:

    1:使用ajax形式:

    <?php
    $errors = empty($model->errors)?'':$model->errors;//页面的验证错误消息
    ?>
    <form action="<?= Yii::$app->urlManager->createUrl('check/check')?>" method="post">
        <div id="btn_area">&nbsp;
            <input type="submit" id="sub_btn" value="登&nbsp;&nbsp;录">&nbsp;&nbsp;
            <input type="text" style="width: 100px;" class="verify" name="Check[verifyCode]">
            <span><img id='img_id' alt="点击刷新" width='85' height='30' /></span>
            <div style="color: red"><?= empty($errors['verifyCode'])?'':yii\helpers\Html::encode($errors['verifyCode']['0'])?></div>
        </div>
    </form>
    <script type="text/javascript" src="/js/jquery.js"></script>
    <script>
        $(document).ready(function() {
            var changeimgsrc = function(){
                $.getJSON("<?php echo Yii::$app->urlManager->createUrl(['check/captcha','refresh'=>'true'])?>",function(res){
                    var _captcha = $("#img_id");
                    _captcha.attr("src","<?php echo Yii::$app->urlManager->createUrl(['check/captcha'])?>"+"?rd="+Math.random());
                });
            };
            changeimgsrc();
            $("#img_id").click(changeimgsrc);
        });
    </script>

    2:使用Yii自带的验证码视图小部件

    <?php
    use 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>

    现象:

    image.png


1 +1