codeigniter login check for all functions(tabs)

2019-08-12 01:02发布

i have a function for login controls. if user didnt login it redirects to login.php

in my controller i have to many functions and this functions represents pages in website. so do i have to call $this->is_logged_in(); function in each function.

for example:

class Admin extends CI_Controller{


        function index(){
            $this->is_logged_in(); // works fine like this
                $this->load->view('admin/welcome_message');
        }

        function users(){
            $this->is_logged_in(); // works fine like this
                $this->load->view('admin/users');
        }

        function comments(){
            $this->is_logged_in(); // works fine like this
                $this->load->view('admin/comments');
        }

}

i dont want to call this function in all function. when i call this in construct result is: infinite loop.

4条回答
你好瞎i
2楼-- · 2019-08-12 01:38

Create your own base controller in your application/core folder and in its constructor do:

class MY_Controller extends CI_Controller {

    public function __construct() 
    {
        parent::__construct();

        // Check that the user is logged in
        if ($this->session->userdata('userid') == null || $this->session->userdata('userid') < 1) {
            // Prevent infinite loop by checking that this isn't the login controller               
            if ($this->router->class != '<Name of Your Login Controller') 
            {                        
                redirect(base_url());
            }
        }   
    }
}

Then all of your controllers just need to inherit your new controller and then all requests will check that the user is logged in.

This can be more specific if required by also checking $this->router->method to match against a specific action.

查看更多
Evening l夕情丶
3楼-- · 2019-08-12 01:45

Add this constructor, and you wont have to write that function on each.

 function __construct() {
           parent::__construct();
           if(!$this->is_logged_in()):
                 redirect(base_url()."login.php");
       }
查看更多
Emotional °昔
4楼-- · 2019-08-12 01:48
public function __construct()
{
    parent::__construct();
        session_start();

        if(!isset($_SESSION['username'])){
            redirect('login');
        }

}

Define who is parent and check the function result. Done

查看更多
ら.Afraid
5楼-- · 2019-08-12 01:52

The best way to do this kind of things is to use hooks Use session data in hooks in codeIgniter

that will be all you should need.

查看更多
登录 后发表回答