dqg2269 2013-08-07 10:41
浏览 74
已采纳

CodeIgniter在每个Controller中验证用户身份

I'm building my first project in Codeigniter, using Tank_auth to handle my CMS authentication.

It's working ok but I have a question about best practices. Currently, every function in every controller has the following structure:

public function add()
    {
        if ($this->tank_auth->is_logged_in())
        {

            $data['stuff'] = 'stuff';

            $this->load->view('admin/cms_add',$data);


        } else
        {
            redirect('/admin/login/');  
        }
    }

With quite a few controllers, and a few functions in each, it's starting to get repetitive, and I wonder if this is the correct way to go about it, or if there's a cleaner method of ensuring non-logged in users can't access these functions.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dsf12123 2013-08-07 10:58
    关注

    If every method in every controller should check whether user is logged-in, you can use __construct() method in each controllers as the following:

    public function __construct()
    {
        parent::__construct();
    
        if (! $this->tank_auth->is_logged_in()) {
            redirect('/admin/login/');
        }
    }
    

    You can also extend the CI Controller and create a custom MY_Controller and check the if statement inside. then the Controllers only accept logged-in users, should inherit the My_Controller:

    application/core/MY_Controller.php:

    class MY_Controller extends CI_Controller {
    
        public function __construct()
        {
            // Execute CI_Controller Constructor
            parent::__construct();
    
            if (! $this->tank_auth->is_logged_in()) {
                redirect('/admin/login/');
            }
        }
    }
    

    application/controllers/welcome.php:

    class Welcome extends MY_Controller {
    
        function __construct()
        {
            parent::__construct();
        }
    
        function index()
        {
            $this->load->view('welcome_message');
        }
    }
    

    Take a look at CI user guide for more info.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀