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条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法