


Detailed explanation of how to use the verification code that comes with Yii 2.0
This article mainly introduces some experiences about 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 come here Let’s take a look.
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' => '',//在官网的教程里是加上了英文字母,我这里先给去掉了,这里去 掉会不会产生影响因为我还没做接收验证,只做了验证码显示的功能,你们可以自己测试下 ]; } /***/
Then in the second step we go to 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 ], ]; }
The second step of the controller code here is It’s done, you should pay attention to the categories to be added and don’t fall behind!
The third step:
In the view template, here is login.php and add the following code
<?php $form = ActiveForm::begin([ 'id' => 'login-form', ]); ?> <?php echo Captcha::widget(['name'=>'captchaimg','captchaAction'=>'login/captcha','imageOptions'=>['id'=>'captchaimg', 'title'=>'换一个', 'alt'=>'换一个', 'style'=>'cursor:pointer;margin-left:25px;'],'template'=>'{image}']);//我这里写的跟官方的不一样,因为我这里加了一个参数(login/captcha),这个参数指向你当前控制器名,如果不加这句,就会找到默认的site控制器上去,验证码会一直出不来,在style里是可以写css代码的,可以调试样式 ?> <?php ActiveForm::end(); ?>
The above is the detailed content of Detailed explanation of how to use the verification code that comes with Yii 2.0. For more information, please follow other related articles on the PHP Chinese website!

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version
