Home Backend Development PHP Tutorial Sharing experience in using the verification code that comes with Yii 2.0

Sharing experience in using the verification code that comes with Yii 2.0

May 03, 2018 pm 03:48 PM
use share experience

This article mainly introduces to you some experience in using the verification code that comes with Yii 2.0, so that novices can get started quickly, and it has certain reference and learning value for everyone. Friends who need it can take a look below.

Preface

In the front-end verification code that comes with the official website, there is a contact.php file under the view. If you have nothing to do, you can take a look first. Without further ado, interested friends can take a look at the detailed introduction:

The usage method is as follows:

Step one: Because I created the modules myself, I created a new models directory under my modules (the default gii-generated modules does not have this directory), and I named it LoginForm.php

The code is as follows:

namespace app\modules\XXX\models;//这个你们写自己的命名空间,我以我的modules项目路径为例

use Yii;

use yii\base\Model;

use yii\captcha\Captcha;

class LoginForm extends Model
{ 
 public $name; 

 public $email; 

 public $subject; 

 public $body; 

 public $verifyCode;//验证码这个变量是必须建的,因为要储存验证码的值` /** * @return array the validation rules. */

 public function rules() 
 { 
   return [ 
     // name, email, subject and body are required 
     [['name', 'email', 'subject', 'body'], 'required'], 
     // email has to be a valid email 
     ['email', 'email'], 
     // verifyCode needs to be entered correctly 
     ['verifyCode', 'captcha'],//注意这里,在百度中查到很多教程,这里写的都不一样,最 简单的写法就像我这种写法,当然还有其它各种写法 
     //['verifyCode', 'captcha','captchaAction'=>'admin/index/captcha','message'=>'验 证码不正确!'], 这种写法在官网自带的LoginForm.php中有写到,大家可以没事看看 ]; 
 }
 /*
 * * @return array customized attribute labels 
 */ 
 public function attributeLabels() 
 { 
   return [ 
     // 'verifyCode' => 'Verification Code', 
     'verifyCode' => '',//在官网的教程里是加上了英文字母,我这里先给去掉了,这里去 掉会不会产生影响因为我还没做接收验证,只做了验证码显示的功能,你们可以自己测试下 
   ]; 
 } 
/***/
Copy after login

Then in the second step we go to the controller and add the code

namespace app\modules\XXX\controllers;//你们自己的控制器空间

use yii\web\Controller;

use yii\web\Session;

use Yii;

use app\modules\XXX\models\LoginForm;//XXX你们自己定义的名字

use yii\filters\AccessControl;

use yii\filters\VerbFilter;

/*
 *这个是对应前台模版的action
 */
public function actionLogin()
{
  $loginForm = new LoginForm();//这里要把刚才写的类new下,注意你们要引入文件路径额
  $this->render('login',array('loginForm'=>$loginForm));//变量传到前台模版
}
/**
 * @用户授权规则
 */
public function behaviors()
{
 return [
   'access' => [
    'class' => AccessControl::className(),
    'only' => ['logout', 'signup','login'],//这里一定要加
    'rules' => [
     [
      'actions' => ['login','captcha'],
      'allow' => true,
      'roles' => ['?'],
     ],
     [
      'actions'=>['logout','edit','add','del','index','users','thumb','upload','cutpic','follow','nofollow'],
      'allow' => true,
      'roles' => ['@'],
     ],
    ],
   ],
   'verbs' => [
    'class' => VerbFilter::className(),
    'actions' => [
     'logout' => ['post'],
    ],
   ],
  ];
 }
 /**
  * @验证码独立操作 下面这个actions注意一点,验证码调试出来的样式也许你并不满意,这里就可
以需修改,这些个参数对应的类是@app\vendor\yiisoft\yii2\captcha\CaptchaAction.php,可以参照这个
类里的参数去修改,也可以直接修改这个类的默认参数,这样这里就不需要改了
  */
 public function actions()
 { 
  return [ 
//     '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
       ],
 ];
 }
Copy after login

The second step of the controller code is completed here. You should pay attention to the classes to be added and don’t miss them!

Step Three:

In the view template, here is login.php and add the following code

 <?php 
   $form = ActiveForm::begin([
        &#39;id&#39; => &#39;login-form&#39;,         
          ]); 
 ?>
<?php 
 echo Captcha::widget([&#39;name&#39;=>&#39;captchaimg&#39;,&#39;captchaAction&#39;=>&#39;login/captcha&#39;,&#39;imageOptions&#39;=>[&#39;id&#39;=>&#39;captchaimg&#39;, &#39;title&#39;=>&#39;换一个&#39;, &#39;alt&#39;=>&#39;换一个&#39;, &#39;style&#39;=>&#39;cursor:pointer;margin-left:25px;&#39;],&#39;template&#39;=>&#39;{image}&#39;]);//我这里写的跟官方的不一样,因为我这里加了一个参数(login/captcha),这个参数指向你当前控制器名,如果不加这句,就会找到默认的site控制器上去,验证码会一直出不来,在style里是可以写css代码的,可以调试样式 ?>
<?php 
ActiveForm::end(); 
?>
Copy after login

Related recommendations:

(5) The upload function that comes with Yii is very easy to use

How to create an application using the command line that comes with Yii


The above is the detailed content of Sharing experience in using the verification code that comes with Yii 2.0. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the &quot;Share to&quot; option at the bottom, and then select the first &quot;WeChat Moments&quot; allows you to share content to WeChat Moments.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use Xiaoai Speaker How to connect Xiaoai Speaker to mobile phone How to use Xiaoai Speaker How to connect Xiaoai Speaker to mobile phone Feb 22, 2024 pm 05:19 PM

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.

See all articles