php - Login verification issue with TP5
巴扎黑
巴扎黑 2017-05-25 15:08:19
0
5
1165

This should be a relatively common problem. When I deal with the front-end and back-end, I need to determine whether there is a session to determine whether the user is logged in.

But the method I saw through the documentation is that I can only introduce a judgment once on each page, and then perform other operations. However, there must be a simpler way to deal with this matter. I really can’t figure it out myself. Please ask someone. help!

The main thing is how to set it up once, and then let all pages in the specified directory determine whether to log in, so as to facilitate the next operation

巴扎黑
巴扎黑

reply all(5)
迷茫

The first type of reference access: write all session judgment and verification in a class. Create a pre-controller method or initialization control in each controller, and directly reference the login verification method of the session class in the method.
The second kind of inheritance: each controller inherits the session verification class, so that every time the controller is accessed, it inherits all the classes and methods of the session, and sets the initialization control in the session class as the login verification of the session

I personally recommend the second option because there is no need to initialize the controller in each controller, which reduces the code and facilitates maintenance

世界只因有你

Write a base class like Base.php,通过其_initialize to implement it, like:

<?php
namespace app\admin\controller;

use think\Controller;

class Base extends Controller{
    public function _initialize(){
        $uid = session('uid');
        if($uid == null){
            $this->rediect('Login/index','请先登录后操作');
        }
    }
}

Among them Login.php不能继承Base.php, otherwise additional special judgment is required, such as:

<?php
namespace app\admin\controller;

use think\Controller;

class Login extends Controller{
    public function _initialize(){
        $uid = session('uid');
        if($uid != null){
            $this->rediect('Index/index','已登录');
        }
    }
}
迷茫

I am also a novice, but I just have an idea. After logging in to store the session, I can write a public method to determine the session on the backend, and then use this method in the required directory, so that there is no need to store it in each directory. It’s time to judge!

只是个人想法,没有实践啊!
Peter_Zhu

Write a verification middleware (behavior), and then call it in the route. You can arbitrarily specify which pages need to call this verification middleware.

You can look at the behavior part in the manual

给我你的怀抱

There is no need to introduce judgment on each page. You can inherit all controllers from a common controller and write a session judgment in the common controller.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template