第一种方式:采用model

1. 模型:Code.php

<?php
namespace app\models;

use yii\base\Model;
class Code extends Model
{
  public $code;//添加的验证码字段

  public function rules()
  {
    return [
      //captchaAction 是生成验证码的控制器
      ['code', 'captcha', 'captchaAction' => 'demo/captcha', 'message' => '验证码不正确'],

    ];
  }
}

控制器:DemoController.php
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;

class DemoController extends Controller
{
  public function actions()
  {
    return [
      'captcha' => [
      'class' => 'yii\captcha\CaptchaAction',
      'maxLength' => 4,
      'minLength' => 4,
      'width' => 80,
      'height' => 40,
      ],
    ];
  }
  public function actionCode()
  {
    $model = new \app\models\Code();
    if(Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
    if($model->valodate) {//验证
      echo '验证成功';
    } else{
      //失败
      var_dump($model->getErrors());
    }
  }
  return $this->render('code', ['model' => $model]);
}
}

HTML :code.php
<?php
use \yii\helpers\Html;
?>
<?= Html::beginForm('', 'post', ['class' => 'form']);?>
<?=\yii\captcha\Captcha::widget([
  'model' =>$model,   //Model
  'attribute' => 'code',   //验证码的字段
  'captchaAction' => 'demo/captcha',   //验证码的action 与 Model是对应的
  'template' => '{input}{image}',   //模板,可以自定义
  'options' => ['id' => 'input'],   //input的HTML属性配置
  'imageOptions' => ['alt' => '点击刷新验证码'],   //image的HTML属性配置
])?>
<?=Html:submitButton('提交', ['class' => 'submit'])?>
<?php ActiveForm::end(); ?>

验证码显示:

第二种方式: 不采用model

2. 控制器:

<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;

class DemoController extends Controller
{
  public function actions()
  {
    return [
      'captcha' => [
      'class' => 'yii\captcha\CaptchaAction',
      'maxLength' => 4,
      'minLength' => 4,
      'width' => 80,
      'height' => 40,
      ],

    ];
  }
  public function actionCodeTwo(){
    if(Yii::$app->request->isPost) {//验证验证码
    $code = $_POST['code'];
    //实例化一个验证码验证对象
    $cpValidate = new yii\captcha\CaptchaValidator();
    //配置action为当前的
    $cpValidate->captchaAction = 'demo/captcha';
    //创建一个验证码对象
    $cpAction = $cpValidate->createCaptchaAction();
    //读取验证码
    $scode = $cpAction->getVerifyCode();
    if($code == $scode) {  

      echo ‘正确’;
    }else{
       echo '错误';
    }

    return $this->render('code');
}

视图:
<?php
use \yii\helpers\Html;
?>
<?= Html::beginForm('', 'post', ['class' => 'form']);?>
<?=\yii\captcha\Captcha::widget([
  'name' => 'code',
  'captchaAction' => 'demo/captcha', //验证码的action 与 Model是对应的
  'template' => '{input}{image}', //模板,可以自定义
  'options' => ['id' => 'input'], //input的HTML属性配置
  'imageOptions' => ['alt' => '点击刷新验证码'], //image的HTML属性配置
])?>
<?=Html:submitButton('提交', ['class' => 'submit'])?>
<?php ActiveForm::end(); ?>

验证码显示:

yii2.0验证码的两种实现方式的更多相关文章

  1. css中两种居中方式text-align:center和margin:0 auto 的使用场景

    关于使用text-align:center和margin:0 auto 两种居中方式的比较 前言:最近由于要学习后端,需要提前学习一部分前端知识,补了补css知识,发现狂神在讲这一部分讲的不是特别清楚 ...

  2. iOS活动倒计时的两种实现方式

    代码地址如下:http://www.demodashi.com/demo/11076.html 在做些活动界面或者限时验证码时, 经常会使用一些倒计时突出展现. 现提供两种方案: 一.使用NSTime ...

  3. Web APi之认证(Authentication)两种实现方式【二】(十三)

    前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...

  4. Android中BroadcastReceiver的两种注册方式(静态和动态)详解

    今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来 ...

  5. struts2+spring的两种整合方式

    也许有些人会因为学习了struts1,会以为struts2.struts1与spring的整合也是一样的,其实这两者相差甚远.下面就来讲解一下struts2与spring的整合两种方案.(部分转载,里 ...

  6. easyui datagride 两种查询方式

    easyui datagride 两种查询方式function doReseach() { //$('#tt').datagrid('load', { // FixedCompany: $('.c_s ...

  7. PlaceHolder的两种实现方式

    placeholder属性是HTML5 中为input添加的.在input上提供一个占位符,文字形式展示输入字段预期值的提示信息(hint),该字段会在输入为空时显示. 如 <input typ ...

  8. Ajax中的get和post两种请求方式的异同

    Ajax中我们经常用到get和post请求.那么什么时候用get请求,什么时候用post方式请求呢? 在做回答前我们首先要了解get和post的区别.   1. get是把参数数据队列加到提交表单的A ...

  9. 第一章 Mybtais的两种启动方式

    Mybatis的两种启动方式如下: 1.xml实现: xml的实现方式中,主要是通过手动创建SqlSession,然后调用session.selectOne()方法实现来实现. 首先是创建Config ...

随机推荐

  1. Linux文件操作常用命令

    一.一些文件操作命令. 1.cd /home  进入"home目录" 2.cd ../ 返回上一级目录 3.cd -  返回上次所在的目录 4.pwd 显示工程路径 5.ll 显示 ...

  2. Python使用协程进行爬虫

    详情点我跳转 关注公众号"轻松学编程"了解更多. 1.协程 协程,又称微线程,纤程.英文名Coroutine. 协程是啥 ?? 首先我们得知道协程是啥?协程其实可以认为是比线程更小 ...

  3. Amdocs收购OPENET:关于5G应用落地的思考

    今年8月,全球通讯和媒体领导者之一Amdocs收购了Openet.在VoltDB,听到这个消息,我们感到非常高兴和自豪!在过去的7年里,我们一直是Openet解决方案的基础数据平台. 尽管许多供应商仍 ...

  4. LR-demo

    from __future__ import print_function   # 导入相关python库 import os import numpy as np import pandas as ...

  5. 初次使用flask

    以写的一个小的例子来记录第一次使用: from flask import Flask, render_template import json # 实例化,可视为固定格式 app = Flask(__ ...

  6. C# type对象

    新建控制台应用程序 新建一个类 class MyClass { private int id; private int age; public int numb; public string Name ...

  7. webpack配置babel篇

    babel-polyfill & babel-runtime & babel-preset-env babel-core babel-core 的作用是把 js 代码分析成 ast , ...

  8. day88:luffy:支付宝同步结果通知&接收异步支付结果&用户购买记录&我的订单

    目录 1.支付宝同步结果通知 2.用户购买记录表 3.接受异步支付结果 4.善后事宜 5.我的订单 1.支付宝同步结果通知 1.get请求支付宝,支付宝返回给你的参数 当用户输入用户名和密码确认支付的 ...

  9. Core WebApi项目快速入门(一):环境部署

    1.WebApi新建与部署 1.1 新建Core WebApi工程 1.2 部署 1.2.1 IIS部署 首先以文件方式发布应用程序,然后下载依赖.net core运行时及host安装包 在iis中看 ...

  10. ssh连接缓慢的问题分析

    之前遇到ssh连接缓慢的问题 一般会检查Server端 /etc/ssh/sshd_config配置文件的两个地方 1.设置UseDNS no 因为我们ssh连接服务器的话 如果UseDNS选项是打开 ...