search
HomeBackend DevelopmentPHP TutorialYii2 Forgot password operation based on email verification

The content of this article is about the forgotten password operation of Yii2 based on email verification. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

I talked about sending emails before function, now we will use the email sending function to make a small demo

Let’s first sort out what process we need to perform to realize the forgotten password

1. 弹出窗口,提示用户输入用户名和邮箱。2. 验证邮箱,利用md5等等加密拼接token,发送token,当前时间戳,账户名等属性。3. 用户点击邮箱链接,到指定控制器,验证我们的token和时间是否超时。4. 如果都验证成功,则进入修改密码操作
  1. If you click Forget Password, we will enter the corresponding method of the current controller.
    Verify the email and user name entered by the user. If the verification is successful, perform our send email operation

//模型文件代码
 public function seekPass($post)
    {
        $this->scenario = "seekPass";        if($this->load($post)&&$this->validate())
        {        $time = time();        $adminuser = $post['Admin']['adminuser'];        
        $token  = $this->createToken($post['Admin']['adminuser'],$time);     
        //自定义方法,创建一个唯一token
        $mailer = \Yii::$app->mailer->compose('seekpass',['text'=>'text','adminuser'=>$post['Admin']['adminuser'],'token'=>$_SERVER['HTTP_HOST'].Url::toRoute(['manage/emailchangepass'])."&timestamp=".$time."&token=".$token."&adminuser=".$adminuser]);            
        $mailer ->setFrom("1115007981@qq.com")
                    ->setTo("1115007981@qq.com")
                    ->setSubject("黑势力科技")
                    ->send();        if($mailer)            return true;
        }        return false;
    }    //拼接的邮箱地址为:

    http://web.demo.com/shop/access/backend/web/index.php?r=manage/Femailchangepass×tamp=1524052534&token=4575d5050f57baf4a896c3924d972c12&adminuser=admin
  1. If we click on the spliced ​​email address, then We will enter the emailchangepass method in our manage controller, and transmit our token, time, and adminuser attributes through the GET method
    In the controller

    In the model layer, we need to write method, there is only the changepass() method. Verify that the updateAll() method is called successfully

  • We need to verify the timeliness of our time. The connection fails after 5 minutes

  • We need to To verify whether the token is the token we initially created

  • we need to identify whether there is a POST request currently. If there is, it means that the user has entered a modified password, and you need to enter the model file to verify the password. Rules

     public function actionEmailchangepass(){
       $this->layout='login';       $time =  Yii::$app->request->get('timestamp');       
       $adminuser = Yii::$app->request->get('adminuser');       $token =  Yii::$app->request->get('token');       $model = new Admin();       $mytoken =  $model->createToken($adminuser,$time);       if($token!=$mytoken)
           {           $this->redirect(['public/login']);
               Yii::$app->end();
           }       if(time()-$time>300)
           {           $this->redirect(['public/login']);
               Yii::$app->end();
           }   if(Yii::$app->request->isPost)
       {       $post = Yii::$app->request->post();      if ($model->changepass($post))
          {
              Yii::$app->session->setFlash('info','密码修改成功');
          }
       }   $model->adminuser = $adminuser;   return $this->render('emailchangepass',['model'=>$model]);
    }

This ends this sharing.

I talked about the email sending function before, now we will use the email sending function to make a small demo

Let’s first understand what process we need to perform to realize the forgotten password

1. 弹出窗口,提示用户输入用户名和邮箱。2. 验证邮箱,利用md5等等加密拼接token,发送token,当前时间戳,账户名等属性。3. 用户点击邮箱链接,到指定控制器,验证我们的token和时间是否超时。4. 如果都验证成功,则进入修改密码操作
  1. If you click Forgot Password, we will enter the corresponding method of the current controller.
    Verify the email and user name entered by the user. If the verification is successful, perform our send email operation

//模型文件代码
 public function seekPass($post)
    {
        $this->scenario = "seekPass";        if($this->load($post)&&$this->validate())
        {        $time = time();        $adminuser = $post['Admin']['adminuser'];        $token  = $this->createToken($post['Admin']['adminuser'],$time);     //自定义方法,创建一个唯一token
        $mailer = \Yii::$app->mailer->compose('seekpass',['text'=>'text','adminuser'=>$post['Admin']['adminuser'],'token'=>$_SERVER['HTTP_HOST'].Url::toRoute(['manage/emailchangepass'])."&timestamp=".$time."&token=".$token."&adminuser=".$adminuser]);            $mailer ->setFrom("1115007981@qq.com")
                    ->setTo("1115007981@qq.com")
                    ->setSubject("黑势力科技")
                    ->send();        if($mailer)            return true;
        }        return false;
    }    //拼接的邮箱地址为:

    http://web.demo.com/shop/access/backend/web/index.php?r=manage/Femailchangepass×tamp=1524052534&token=4575d5050f57baf4a896c3924d972c12&adminuser=admin
  1. If we click on the spliced ​​email address, then We will enter the emailchangepass method in our manage controller, and transmit our token, time, and adminuser attributes through the GET method
    In the controller

    In the model layer, we need to write method, there is only the changepass() method. Verify that the updateAll() method is called successfully

  • We need to verify the timeliness of our time. The connection fails after 5 minutes

  • We need to To verify whether the token is the token we initially created

  • we need to identify whether there is a POST request currently. If there is, it means that the user has entered a modified password, and you need to enter the model file to verify the password. Rules

     public function actionEmailchangepass(){
       $this->layout='login';       $time =  Yii::$app->request->get('timestamp');       $adminuser = Yii::$app->request->get('adminuser');       $token =  Yii::$app->request->get('token');       $model = new Admin();       $mytoken =  $model->createToken($adminuser,$time);       if($token!=$mytoken)
           {           $this->redirect(['public/login']);
               Yii::$app->end();
           }       if(time()-$time>300)
           {           $this->redirect(['public/login']);
               Yii::$app->end();
           }   if(Yii::$app->request->isPost)
       {       $post = Yii::$app->request->post();      if ($model->changepass($post))
          {
              Yii::$app->session->setFlash('info','密码修改成功');
          }
       }   $model->adminuser = $adminuser;   return $this->render('emailchangepass',['model'=>$model]);
    }

This ends this sharing.

Related recommendations:

yii2 resetful authorization verification

Yii2.0 PHP using Sphinx

The above is the detailed content of Yii2 Forgot password operation based on email verification. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

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

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

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.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

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

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

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.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

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

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

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.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

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

See all articles

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

SecLists

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool