【问题标题】:Session check not working in constructor in Codeigniter PHP会话检查在 Codeigniter PHP 的构造函数中不起作用
【发布时间】:2021-07-07 06:19:47
【问题描述】:

我正在使用 Codeigniter PHP。

我希望如果管理员没有登录,那么他就看不到管理面板页面。 为此我创建了助手。

如果我将条件设置为每个函数,代码就可以工作,但如果我在“构造函数”中使用此代码,则重定向到主页,但在主页之后还会显示“登录”页面。

我哪里错了?

这是我的代码(在我的一个正在工作的函数中使用)

public function admin_offers(){
        if (!is_logged_in()) {
            $this->index();
            //die();
        }
        else {
            $data['offers']=$this->db->get('offers')->result();
            $this->load->view('admin/special-offers',$data);
        }
    }

这是我在构造函数中的代码,对我不起作用。

public function __construct() {
    

    parent::__construct();
        $this->load->model("stores_model");
            $this->load->library("pagination");
            $this->load->library('encryption');
            is_logged_in(); 
            if (!is_logged_in()) {
                $this->index();
            }
}

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    首先,从您的代码中,您调用了该函数两次,这是不必要的。

    is_logged_in(); //this calls the function
    if (!is_logged_in() /* this too */) {
        $this->index();
    }
    

    对于你的情况,试试这个:

    function __construct(){
      parent::__construct();
        $this->load->model("stores_model");
        $this->load->library("pagination");
        $this->load->library('encryption');
         
        if (!$this->session->user_data('session_name')) {
            redirect('controller_name/function'); // the public page
         }
    }
    

    基本上,代码的作用是检查会话数据(登录期间设置)是否存在,如果不存在,则将用户重定向到公共页面(可能是登录页面)。

    如果将代码放在 __construct 函数下,则无需将其包含在单独的函数中,因为此代码在类实例化时执行,因此在加载函数之前执行。

    注意:确保您已经在自动加载中加载了会话库

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      相关资源
      最近更新 更多