Table of Contents
A new method for handling front and back logins in Yii, a new method for yii
Articles you may be interested in:
Home Backend Development PHP Tutorial Implement a new method of handling front and backend login in Yii, yii new method_PHP tutorial

Implement a new method of handling front and backend login in Yii, yii new method_PHP tutorial

Jul 12, 2016 am 09:02 AM
yii Log in

A new method for handling front and back logins in Yii, a new method for yii

This article describes a new method for handling front and back logins in Yii. Share it with everyone for your reference, the details are as follows:

Because I am currently working on a project that involves front and backend login issues, I handle the backend as a module. I see many people put two entry files index.php and admin.php, and then point to the frontend and backend respectively. Although this method is very good, it can completely separate the front and backend, but I always feel that this method is a bit far-fetched. What is the difference between this and the two applications? It is better to make two apps using one framework. And the official Yii background usage method is also to use Module. But Moudle's method has a very troublesome problem, that is, when using Cwebuser to log in, there will be a problem of logging in and logging out at the same time in the front and backend, which is obviously unreasonable. It took me a long time to find the method that will be introduced below. Of course, many of them were based on other people's methods and I made slight changes. My initial approach was to set up an isadmin session when logging in to the backend, and then log out of the session when logging in to the frontend. This could only tell whether it was a frontend login or a background login, but it couldn't log in both the frontend and the backend at the same time, that is, frontend login. Log out after logging into the background, and log out after logging into the front desk. The root cause of this problem is that we use the same Cwebuser instance and cannot set up front and backend sessions at the same time. To solve this problem, we must use different Cwebuser instances to log in to the front and backend. The following is my approach. First, look at the configuration of the front-end user (Cwebuser) in protected->config->main.php:

'user'=>array(
  'class'=>'WebUser',//这个WebUser是继承CwebUser,稍后给出它的代码
  'stateKeyPrefix'=>'member',//这个是设置前台session的前缀
  'allowAutoLogin'=>true,//这里设置允许cookie保存登录信息,一边下次自动登录
),

Copy after login

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

<&#63;php
class 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();//这步是调用main.php里的配置文件
    // import the module-level models and componen
    $this->setImport(array(
      'admin.models.*',
      'admin.components.*',
    ));
    //这里重写父类里的组件
    //如有需要还可以参考API添加相应组件
    Yii::app()->setComponents(array(
        'errorHandler'=>array(
            'class'=>'CErrorHandler',
            'errorAction'=>'admin/default/error',
        ),
        'admin'=>array(
            'class'=>'AdminWebUser',//后台登录类实例
            'stateKeyPrefix'=>'admin',//后台session前缀
            'loginUrl'=>Yii::app()->createUrl('admin/default/login'),
        ),
    ), false);
    //下面这两行我一直没搞定啥意思,貌似CWebModule里也没generatorPaths属性和findGenerators()方法
    //$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;
  }
}
&#63;>

Copy after login

The init() method of AdminModule is to configure another login instance for the backend, let the front and backend use different CWebUser, and set the backend session prefix to distinguish it from the frontend session (they are stored in the $_SESSION array, you You can print it out and see).

In this way, the front and back logins have been separated, but if you log out at this time, you will find that the front and backends have logged out together. So I found the logout() method and found that it has a parameter $destroySession=true. It turns out that if you just logout(), all sessions will be logged out. If you add a false parameter, only the current login instance will be logged out. session, which is why it is necessary to set the front and back session prefixes. Let’s see how the logout method with the false parameter is set 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]);
  }
}

Copy after login

Did you see that you use the matching prefix to log out?

At this point, we can separate the front and back logins and exits. This makes it more like an application, right? Hehe...

I almost forgot to explain:

Yii::app()->user //前台访问用户信息方法
Yii::app()->admin //后台访问用户信息方法

Copy after login

If you don’t understand, take a closer look at the configuration of CWebUser in the front and backend just now.

Attachment 1: WebUser.php code:

<&#63;php
class 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);
  }
}
&#63;>

Copy after login

Attachment 2: AdminWebUser.php code

<&#63;php
class 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);
  }
}
&#63;>

Copy after login

Attachment 3: Front-end UserIdentity.php code

<&#63;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;
  }
}

Copy after login

Attachment 4: Backend UserIdentity.php code

<&#63;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;
  }
}

Copy after login

I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.

Articles you may be interested in:

  • yii user registration form verification example
  • Comprehensive form verification rules of PHP Yii framework
  • Yii framework form form usage Example
  • Yii form generator usage example that does not rely on Model
  • Yii framework form model usage and submitting form data in array form example
  • Yii method of using Captcha verification code
  • Yii’s method of removing asterisks in required fields

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1085882.htmlTechArticleA new method to implement front-end and back-end login processing in Yii, a new method in yii This article describes the implementation of front-end and back-end processing in Yii New way to log in. Share it with everyone for your reference, the details are as follows: Because...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the &quot;Login&quot; button. (2) Select &quot;Retrieve Password&quot;. (3) Enter the mobile phone number you used when registering your account

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! 'Onmyoji' Ibaraki Doji's collection skin can be obtained as soon as you log in, and the new Zen Heart Cloud Mirror skin will be launched soon! Jan 05, 2024 am 10:42 AM

Thousands of ghosts screamed in the mountains and fields, and the sound of the exchange of weapons disappeared. The ghost generals who rushed over the mountains, with fighting spirit raging in their hearts, used the fire as their trumpet to lead hundreds of ghosts to charge into the battle. [Blazing Flame Bairen·Ibaraki Doji Collection Skin is now online] The ghost horns are blazing with flames, the gilt eyes are bursting with unruly fighting spirit, and the white jade armor pieces decorate the shirt, showing the unruly and wild momentum of the great demon. On the snow-white fluttering sleeves, red flames clung to and intertwined, and gold patterns were imprinted on them, igniting a crimson and magical color. The will-o'-the-wisps formed by the condensed demon power roared, and the fierce flames shook the mountains. Demons and ghosts who have returned from purgatory, let's punish the intruders together. [Exclusive dynamic avatar frame·Blazing Flame Bailian] [Exclusive illustration·Firework General Soul] [Biography Appreciation] [How to obtain] Ibaraki Doji’s collection skin·Blazing Flame Bailian will be available in the skin store after maintenance on December 28.

How to log in to Kuaishou PC version - How to log in to Kuaishou PC version How to log in to Kuaishou PC version - How to log in to Kuaishou PC version Mar 04, 2024 pm 03:30 PM

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

How to log in to two devices on Quark How to log in to two devices on Quark Feb 23, 2024 pm 10:55 PM

How to log in to two devices with Quark? Quark Browser supports logging into two devices at the same time, but most friends don’t know how to log in to two devices with Quark Browser. Next, the editor brings users Quark to log in to two devices. Method graphic tutorials, interested users come and take a look! Quark Browser usage tutorial Quark how to log in to two devices 1. First open the Quark Browser APP and click [Quark Network Disk] on the main page; 2. Then enter the Quark Network Disk interface and select the [My Backup] service function; 3. Finally, select [Switch Device] to log in to two new devices.

How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? Mar 23, 2024 pm 05:31 PM

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the &quot;Login&quot; button and select &quot;Account and Password Login&quot;; 3. Click the &quot;Forgot your password?&quot; button; 4. Enter your account number. Click &quot;Next&quot;; 5. The system will send a verification code to your mobile phone, enter the verification code and click &quot;OK&quot;; 6. Set a new password and confirm. You can also use a third-party account (such as

How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance Mar 13, 2024 pm 04:58 PM

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.​

See all articles