CodeIgniter: checking if user logged in for multiple pages

后端 未结 4 443
我在风中等你
我在风中等你 2020-12-12 22:52

I have a controller, which maps to section of my site and all of the pages within it (methods) should only appear if the user is logged in. Otherwise they should be redirect

4条回答
  •  一个人的身影
    2020-12-12 23:34

    You can run code in every method of a Controller by running it in the __construct() method:

    function __construct()
    {
        parent::__construct();
        if ( ! $this->session->userdata('logged_in'))
        { 
            // Allow some methods?
            $allowed = array(
                'some_method_in_this_controller',
                'other_method_in_this_controller',
            );
            if ( ! in_array($this->router->fetch_method(), $allowed)
            {
                redirect('login');
            }
        }
    }
    

    You can remove the "allowed" bits if you want to restrict access to the whole thing, but there are better ways to do this, like creating a base controller:

    // Create file application/core/MY_Controller.php
    class Auth_Controller extends CI_Controller {
    
        function __construct()
        {
            parent::__construct();
            if ( ! $this->session->userdata('logged_in'))
            { 
                redirect('login');
            }
        }
    }
    

    Then have your restricted controllers extend Auth_Controller instead of CI_Controller. Now your code will be run every time the controller is loaded.

    More info on extending core classes: http://www.codeigniter.com/user_guide/general/core_classes.html#extending-core-class

    Also of interest: http://php.net/manual/en/language.oop5.decon.php

提交回复
热议问题