CodeIgniter only allow access to certain controllers when logged in

爷,独闯天下 提交于 2019-12-07 08:59:03

问题


I have some CodeIgniter controllers which should only be accessed by users who have logged in (i.e. where $this->session->userdata('username') is not null). If a non-authenticated person attempts to access said controllers they should receive:

header('location: /auth/login');

There has got to be a better way to do this than to put a

if (!$this->session->userdata('username'))
    header('location: /auth/login');
else
{
    [rest of function]
}

in front of every function in the controller...

I know DX_Auth has a similar functionality, but I am not using an authentication plugin and I am not open to doing so.

Thanks!
Mala


回答1:


Do the user login check when the class is created, so it doesn't matter what function the user is accessing it will check for the session variable and redirect to the login page on failure:

function className()
{
    parent::Controller();
    if(!$this->session->userdata('username')) header('location: /auth/login');
}

That's the way of calling the __constructor or it's equivalent in codeigniter when you create controllers/models, or at least that's what I understood!



来源:https://stackoverflow.com/questions/2020815/codeigniter-only-allow-access-to-certain-controllers-when-logged-in

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