0

我正在创建一个登录检查功能。但是我的两条闪存数据信息设置不正确。

  1. 如果用户已登录,然后如果会话过期,则应设置此闪存数据消息您的会话令牌已过期!
  2. 如果用户尚未登录并尝试访问未登录的控制器,则应设置此 flashdata 消息您需要登录才能访问此站点!

由于某种原因,它总是显示第二条 flashdata 消息。

问题:我怎样才能正确使用这两个 flashdata 消息。

控制器: Login.php 功能:检查

public function check() {
    $uri_route = basename($this->router->directory) .'/'. $this->router->fetch_class();

    $route = isset($uri_route) ? $uri_route : '';

        $ignore = array(
            'common/login',
            'common/forgotten',
            'common/reset'
        );

        if (!in_array($route, $ignore)) {

            // $this->user->is_logged() returns the user id

            if ($this->user->is_logged()) {

                // $this->session->userdata('is_logged') returns true or false

                if (!$this->session->userdata('is_logged')) {

                    // Redirects if the user is logged on and session has expired!

                    $this->session->set_flashdata('warning', 'Your session token has expired!');

                    redirect('admin/common/login');
                }

            } else {

                $this->session->set_flashdata('warning', 'You need to login to access this site!');

                redirect('admin/common/login');

            }
    }

我通过 codeigniter 钩子运行函数,这样我就不必在每个控制器上添加它。

$hook['pre_controller'] = array(
        'class'    => 'Login',
        'function' => 'check',
        'filename' => 'Login.php',
        'filepath' => 'modules/admin/controllers/common'
);
4

1 回答 1

1

你试图通过 uri() 检查什么实际上是一种非常糟糕的检查方式,你还应该将登录检查作为一个构造函数而不是单一的......这是你的函数应该是什么样子:

    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');
           }
        }
    }
于 2015-11-21T05:15:55.647 回答