get the requested controller in hook precontroller in codeigniter

杀马特。学长 韩版系。学妹 提交于 2019-12-13 01:34:01

问题


I'm trying to make a simple routing rule to allow only authenticated users to certain controllers.

To achieve this, I would like to run precontroller hook and check if the user is logged in using ci session. However, I have to know which controller the user wants to access. How do I know this in a hook function?


回答1:


$this->router->fetch_class();

Extend CI_Controller and this should work.




回答2:


I dont think that hooks are best practice for what you want to achieve here

you may try the following: You need to create middle controller that you will extend instead of CI_Controller that will have authentication check and redirect the user to right controller

read this tutorial created by jondavidjohn step by step

http://jondavidjohn.com/blog/2011/01/scalable-login-system-for-codeigniter-ion_auth

You shoud be able to get the idea after 10 mins




回答3:


Cant you just put the authentication on the controller constructor ? It will be called when item instantiate and you can do the check there. Also you can always extend the CI_Controller and put the logic in there so that you can do your check in there (and use this->router->fetch_class() as suggested).




回答4:


If you don't want to go the extended controller route, and I can see your logic there, then you have to use native PHP here because the CI object doesn't exist in the pre_controller_hook.

So, get the URI, then parse it to find the controller:

$uri = $_SERVER['REQUEST_URI'];
$segments = explode("/", $uri);

// if you're removing index.php from your urls, then
$controller = $segments[0];

// if you're not removing index.php
$controller = $segments[1];



回答5:


Extend CI_Controller in your autoload library Class.

Something like this:

class MyAuthLibrary extends CI_Controller {
    var $ci;

    function __construct() {

        $this->ci = &get_instance();
        $route = $this->ci->router->fetch_class();

        if( ($route !== 'login') && !$this->ci->session->userdata('email_address') ) {
            redirect('login');
        } 
    }

}


来源:https://stackoverflow.com/questions/13984234/get-the-requested-controller-in-hook-precontroller-in-codeigniter

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