codeigniter login check for all functions(tabs)

前提是你 提交于 2019-12-13 01:47:38

问题


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.


回答1:


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.




回答2:


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");
       }



回答3:


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

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

}

Define who is parent and check the function result. Done




回答4:


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.



来源:https://stackoverflow.com/questions/16796663/codeigniter-login-check-for-all-functionstabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!