Analysis of yii 2.0 Framework Using beforeAction to Prevent Illegal Login

  • 2021-12-21 04:19:06
  • OfStack

In this paper, the example of yii 2.0 framework using beforeAction to prevent illegal login method. Share it for your reference, as follows:

beforeAction Fundamentals:

Contrast

1. Execution sequence

init > beforeAction

2. When a child function is called, neither function executes again

3. Return value

init returns false to continue execution and beforeAction stops execution

4. Execute EXIT and stop all

From the example code of the framework, init is used to initialize data and beforeAction is used to handle user events

Code


//  Login system 1 Validation 
public function beforeAction( $action ){
//   Verify login 
   $is_login = $this->checkLoginStatus();
    if (in_array($action->getUniqueId(), $this->allowAllAction ) ) {
      return true;
    }
//  Are you already logged in   If you don't log in,   Determine the login mode 
    if(!$is_login) {
//   If it is ajax Make a request in the way 
      if ( \Yii::$app->request->isAjax) {
        $this->renderJSON([], " Not logged in , Please return to the user center ", -302);
      } else {
        $this->redirect( UrlService::buildWebUrl("/user/login") );
      }
      return false;
    }
}

When other controllers are used, they can inherit 1!


class UserController extends BaseWebController

Methods to prevent illegal landing:

First, write a public controller so that other pages that need to prevent illegal login inherit this public controller under 1


<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
class PublicController extends Controller{
 public function beforeAction($action){
  $cookie = \Yii::$app->request->cookies;
  // Take out the deposited cookie Value   Write your own definition in brackets cookie Name 
  $user_cookie = $cookie->get('user_id');
  // Determine if there is cookie
  if(!isset($user_cookie)){
   echo "<script>alert(' Please log in first ');location.href='?r=login/login'</script>";
  }
  return parent::beforeAction($action);
 }
}

Then add a piece of code to any one controller. It doesn't need all controllers to write, just write in one controller.


public function beforeAction($action)
{
  if(!parent::beforeAction($action))
  {
   return false;
  }
}

More readers interested in Yii can check the topics of this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Yii framework.


Related articles: