我是codeigniter的新手,我已经完成了一个登录页面,但它不起作用。 我想通过使用会话代码。我需要把session_start();在每个控制器中,或者在codeigniter中有一种方法,它将自动在所有控制器中? (我应该这样做吗?)。
function __construct() // controller
{
parent::__construct();
$this->load->library('session');
$this->load->database();
$this->load->helper('url');
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->model('np_login_model');
}
public function index()
{
$this->load->view('admin/login/login_dashboard');
}
// Check for user login process
public function user_login_process()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
if(isset($this->session->userdata['logged_in']))
{
$this->load->view('admin/intropage');
}
else
{
$this->load->view('admin/login/login_dashboard');
}
}
else
{
$data = array('username' => $this->input->post('username'),'password' => $this->input->post('password'));
$result = $this->np_login_model->login($data);
if ($result == TRUE)
{
$username = $this->input->post('username');
$result = $this->np_login_model->read_user_information($username);
if ($result != false)
{
$session_data = array('username' => $result[0]->user_name);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('admin/intropage');
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('admin/login/login_dashboard', $data);
}
}
}
模型
public function login($data)
{
$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('np_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($username) {
$condition = "user_name =" . "'" . $username . "'";
$this->db->select('*');
$this->db->from('np_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
答案 0 :(得分:2)
使用此$this->session->userdata('logged_in')
代替$this->session->userdata['logged_in']
希望帮助