Yii2.0验证码详细教程。 [ 2.0 版本 ]
几天前开始做验证码,我之前是学Thinkphp的,到了这里感觉很没有头绪,然后上网找,找了半天都只是添加,愁死了。都没有验证,这里给大家补齐。还有人提到了--刷新页面验证码不变,我查了好久, 终于在自己家里看到了这个文章,谢谢
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' => '请在右面输入验证码  懂不?',
        ];
    }
}
?>
第一步就完成了。开始第二步,建一个控制器
<?php
namespace 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。
<?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>
?>
好嘞。 问题总结1.刷新页面更改验证码。在此再次感谢作者的总结。原文刷新页面且验证码变化的出处  还有问题的留言。。。以后会有修改**
小白小
            注册时间:2016-04-22
最后登录:2021-02-18
在线时长:16小时42分
    最后登录:2021-02-18
在线时长:16小时42分
- 粉丝7
- 金钱310
- 威望30
- 积分770



共 8 条评论
啦啦啦啦啦啦
改好了。。。。。累死了
把我的问题解决了
简单的教程,几步就能搞定验证码,点击链接查看教程http://www.yii-china.com/post/detail/12.html
function function_name() { echo 'hello world'; }什么鬼。。。
很详细 给作者赞一个
PHP User Error – yii\base\ErrorException
我也是这样,姿势不对吗?
可以问一下 actions 方法是什么作用吗?
不可以^_^