Yii implements a new method for handling frontend and backend login, yii new method _ PHP Tutorial

Source: Internet
Author: User
Yii implements a new method to process frontend and backend logon, and yii implements a new method. Yii implements a new method to process frontend and backend logon. yii introduces the new method to process frontend and backend logon in Yii. For your reference, the Yii method is as follows:

This example describes how to process frontend and backend logon in Yii. We will share this with you for your reference. The details are as follows:

Recently, a project involves frontend and backend login. I use the backend as a Module. I think many people put two entry files, index. php and admin. php, and point them to the front-end and backend. This method is good and can completely separate the front and back ends, but I always think this method is a little far-fetched. what is the difference between this method and the two applications? It is better to use one framework for two apps. In addition, the official Yii background uses the Module method. However, the Moudle method has a headache, that is, when using Cwebuser to log on, the system may log on and exit together in the front and back, which is obviously unreasonable. I have struggled for a long time to find the method that will be introduced below. of course, many of them refer to others and I made some changes myself. At first, I set an isadmin session when logging on to the background, and then log off the session when logging on to the foreground. in this way, I can only identify whether the session is logged on at the foreground or at the background, however, you cannot log on to the frontend and backend. that is, if you log on to the frontend, the backend is logged out. The root cause for this is that we use the same Cwebuser instance and cannot set the frontend and backend sessions at the same time. to solve this problem, we need to use different Cwebuser instances in the front and backend to log on. The following is my practice. First, let's look at the configuration of the front-end user (Cwebuser) in protected-> config-> main. php:

'User' => array ('class' => 'webuser', // This WebUser inherits the CwebUser. the code 'statekeyprefix' => 'Member 'will be provided later ', // This is the prefix of the front-end session 'allowautologin' => true, // here it is set to allow the cookie to save the login information, while the next automatic login ),

When you use Gii to generate an admin module (that is, the background module name), an AdminModule is generated under module-> admin. php file, which inherits the CWebModule class. the code for this file is given below. The key is in this file. I hope you will study it carefully:

<? Phpclass AdminModule extends CWebModule {public function init () {// this method is called when the module is being created // you may place code here to customize the module or the application parent :: init (); // This step calls main. php configuration file // import the module-level models and componen $ this-> setImport (array ('admin. models. * ', 'admin. components. * ',); // rewrite the components in the parent class here. // if necessary, you can refer to the API to add the corresponding components Yii: app ()-> setCompon Ents (array ('errorhandler' => array ('class' => 'cerrorhandler', 'erroraction' => 'admin/default/error ',), 'admin' => array ('class' => 'adminwebuser', // background logon class instance 'statekeyprefix' => 'admin ', // background session prefix 'loginurl' => Yii: app ()-> createUrl ('admin/default/login'), false ); // the following two lines have not been completed. it seems that the generatorPaths attribute and findGenerators () method are not included in the CWebModule. // $ this-> generatorPaths [] = 'admin. generators '; // $ this-> controllerMap = $ This-> findGenerators ();} public function beforeControllerAction ($ controller, $ action) {if (parent: beforeControllerAction ($ controller, $ action )) {$ route = $ controller-> id. '/'. $ action-> id; if (! $ This-> allowIp (Yii: app ()-> request-> userHostAddress) & $ route! = 'Default/error') throw new CHttpException (403, "You are not allowed to access this page. "); $ publicPages = array ('default/login', 'default/error',); if (Yii: app ()-> admin-> isGuest &&! In_array ($ route, $ publicPages) Yii: app ()-> admin-> loginRequired (); else return true;} return false;} protected function allowIp ($ ip) {if (empty ($ this-> ipFilters) return true; foreach ($ this-> ipFilters as $ filter) {if ($ filter = '*' | $ filter = $ ip | ($ pos = strpos ($ filter ,'*'))! = False &&! Strncmp ($ ip, $ filter, $ pos) return true;} return false ;}}?>

The init () method of AdminModule is to configure another logon instance for the backend, so that different cwebusers can be used in the front and backend, and set the background session prefix, in order to distinguish it from the front-end session (their colleagues exist in the $ _ SESSION array, you can print it out ).

In this way, the frontend and backend logon points have been removed. However, if you exit, you will find that the frontend and backend are exited together. So I found the logout () method and found that it has a parameter $ destroySession = true. it turns out that, if you only use logout (), all sessions will be logged out, if the parameter "false" is added, only the session of the currently logged-on instance will be logged out, which is why the prefix of the session in the front and back ends should be set, the following shows how the logout method with the false parameter is used to log out the session:

/*** Clears all user identity information from persistent storage. * This will remove the data stored via {@link setState}. */public function clearStates(){  $keys=array_keys($_SESSION);  $prefix=$this->getStateKeyPrefix();  $n=strlen($prefix);  foreach($keys as $key)  {    if(!strncmp($key,$prefix,$n))      unset($_SESSION[$key]);  }}

No, it is deregistered by matching the prefix.

At this point, we can separate the front-and back-end logon and exit the separation. This is more like an application, right? Hey...

I almost forgot to explain:

Yii: app ()-> user // method for accessing user information on the foreground Yii: app ()-> admin // method for accessing user information on the background

Take a closer look at the configuration of CWebUser in the front and back end.

Appendix 1: WebUser. php code:

<?phpclass WebUser extends CWebUser{  public function __get($name)  {    if ($this->hasState('__userInfo')) {      $user=$this->getState('__userInfo',array());      if (isset($user[$name])) {        return $user[$name];      }    }    return parent::__get($name);  }  public function login($identity, $duration) {    $this->setState('__userInfo', $identity->getUser());    parent::login($identity, $duration);  }}?>

Attachment 2: AdminWebUser. php code

<?phpclass AdminWebUser extends CWebUser{  public function __get($name)  {    if ($this->hasState('__adminInfo')) {      $user=$this->getState('__adminInfo',array());      if (isset($user[$name])) {        return $user[$name];      }    }    return parent::__get($name);  }  public function login($identity, $duration) {    $this->setState('__adminInfo', $identity->getUser());    parent::login($identity, $duration);  }}?>

Attachment 3: front-end UserIdentity. php code

<?php/** * UserIdentity represents the data needed to identity a user. * It contains the authentication method that checks if the provided * data can identity the user. */class UserIdentity extends CUserIdentity{  /**   * Authenticates a user.   * The example implementation makes sure if the username and password   * are both 'demo'.   * In practical applications, this should be changed to authenticate   * against some persistent user identity storage (e.g. database).   * @return boolean whether authentication succeeds.   */  public $user;  public $_id;  public $username;  public function authenticate()  {    $this->errorCode=self::ERROR_PASSWORD_INVALID;    $user=User::model()->find('username=:username',array(':username'=>$this->username));     if ($user)    {      $encrypted_passwd=trim($user->password);      $inputpassword = trim(md5($this->password));      if($inputpassword===$encrypted_passwd)      {        $this->errorCode=self::ERROR_NONE;        $this->setUser($user);        $this->_id=$user->id;        $this->username=$user->username;        //if(isset(Yii::app()->user->thisisadmin))          // unset (Yii::app()->user->thisisadmin);      }      else      {        $this->errorCode=self::ERROR_PASSWORD_INVALID;      }    }    else    {      $this->errorCode=self::ERROR_USERNAME_INVALID;    }    unset($user);    return !$this->errorCode;  }  public function getUser()  {    return $this->user;  }  public function getId()  {    return $this->_id;  }  public function getUserName()  {    return $this->username;  }  public function setUser(CActiveRecord $user)  {    $this->user=$user->attributes;  }}

Appendix 4: background UserIdentity. php code

<?php/** * UserIdentity represents the data needed to identity a user. * It contains the authentication method that checks if the provided * data can identity the user. */class UserIdentity extends CUserIdentity{  /**   * Authenticates a user.   * The example implementation makes sure if the username and password   * are both 'demo'.   * In practical applications, this should be changed to authenticate   * against some persistent user identity storage (e.g. database).   * @return boolean whether authentication succeeds.   */  public $admin;  public $_id;  public $username;  public function authenticate()  {    $this->errorCode=self::ERROR_PASSWORD_INVALID;    $user=Staff::model()->find('username=:username',array(':username'=>$this->username));     if ($user)    {      $encrypted_passwd=trim($user->password);      $inputpassword = trim(md5($this->password));      if($inputpassword===$encrypted_passwd)      {        $this->errorCode=self::ERROR_NONE;        $this->setUser($user);        $this->_id=$user->id;        $this->username=$user->username;        // Yii::app()->user->setState("thisisadmin", "true");      }      else      {        $this->errorCode=self::ERROR_PASSWORD_INVALID;      }    }    else    {      $this->errorCode=self::ERROR_USERNAME_INVALID;    }    unset($user);    return !$this->errorCode;  }  public function getUser()  {    return $this->admin;  }  public function getId()  {    return $this->_id;  }  public function getUserName()  {    return $this->username;  }  public function setUser(CActiveRecord $user)  {    $this->admin=$user->attributes;  }}

I hope this article will help you design PHP programs based on the Yii Framework.

Articles you may be interested in:
  • Yii user registry ticket verification instance
  • PHP Yii Framework-table verification rules
  • Yii Framework form usage example
  • Example of Yii form builder usage independent of Model
  • Yii Framework form model usage and example of submitting form data in array form
  • Yii Captcha verification code
  • Yii removes the star number in the required field

The example in this article describes how to process frontend and backend logon in Yii. For your reference, the details are as follows...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.