CodeIgniter 中的会话错误

Error with sessions in CodeIgniter

以下代码片段返回错误,但是当没有 SESSION 时错误消失。

这是错误所指的行:

$user_id = $this->session->userdata('user_id');

这是上一行包含的 class 定义:

class Dashboard extends CI_Controller
{

    public function _construct()
    {        
        parent::_construct();
        $user_id = $this->session->userdata('user_id');
        if(!user_id){
            $this->logout();
        }
    }


    public function index()
    {        
          $this->load->view('dashboard/inc/header_view');
          $this->load->view('dashboard/dashboard_view');
          $this->load->view('dashboard/inc/footer_view');
    }

    public function logout()
    {
        $this->sess_destroy();
        redirect('/');
    }

}

我做错了什么?

请确保您已加载会话库。

$this->load->library('session');

关于您的注销功能

其中 $this->sess_destroy();

替换为 $this->session->sess_destroy(); 因为您缺少 session

确保 $this->load->library('session'); 已加载。

public function _construct() {        
    parent::_construct();

    $this->load->library('session'); // Or Autoload it.

    if ($this->session->userdata('user_id') == FALSE) {
        $this->logout();
    }
}

首先加载会话库。要加载会话,请使用以下方法之一。

 public function _construct()
    {        
        parent::_construct();
        $this->load->library('session');
        $user_id = $this->session->userdata('user_id');
        if(!user_id){
            $this->logout();
        }
    }

或在config/autoload.php

$autoload['libraries'] = array('session');

是的,谢谢 Abdula、wofgang、wyz 现在可以了,dashboard.php(控制器)没有错误,但 user.php(控制器)错误:

这是 user.php 中的错误:

遇到了一个PHP错误

严重性:通知

消息:未定义属性:用户::$user_model

文件名:controllers/user.php

行号:19

回溯:

文件:C:\wamp\www\apcodeigniter\application\controllers\user.php 线路:19 函数:_error_handler

文件:C:\wamp\www\apcodeigniter\index.php 线路:292 函数:require_once

错误行:

$data = $this->user_model->get(1);

行:

$result = $this->user_model->delete($user_id);

和错误行 19:

 $result = $this->user_model->get([
       'login' => $login,
       'password' => hash('sha256', $password . SALT)
   ]);