【发布时间】:2020-05-24 00:33:36
【问题描述】:
从一个控制器重定向到另一个控制器时,会话无法正常工作。在下面的示例中,我只是尝试检查登录,如果有效用户则将用户名设置为来自名为“登录”的控制器的会话,并重定向到另一个控制器“测试”并打印会话值。但是,当用户被验证时,会话可以正常工作,直到我们进入登录控制器(我通过删除重定向方法输入print_r($this->session->userdata('username')); 进行检查)并且当我重定向时,会话值在重定向控制器中显示为空。
这是我的代码示例:
控制器:Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('M_login');
$this->load->helper('url');
$this->load->library('session');
$this->load->helper('form');
}
public function index()
{
$u=$this->session->userdata('username');
if($u) {
redirect('Testing');
} else {
$this->load->view('login');
}
}
public function login_form()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if($this->form_validation->run()==FALSE)
{
$this->load->view('login');
}
else{
$result = $this->M_login->takeUser();
if(count($result)>0)
{
$user = $this->input->post('username', TRUE);
$this->session->set_userdata('username', $username);
redirect('Testing');
}
else{
?>
<script>
alert('Failed Login: Check your username and password!');
history.go(-1);
</script>
<?php
}
}
}
public function logout()
{
$this->session->sess_destroy();
redirect('login/login_form');
}
}
型号:M_login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_login extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function takeUser()
{
$username = $this->input->post('username');
$password1 = $this->input->post('password');
$password = md5($password1);
$this->db->select('username');
$this->db->from('employee');
$this->db->where('username', $username);
$this->db->where('password', $password);
$result = $this->db->get();
return $result->row_array();
}
}
控制器:Testing.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Testing extends CI_Controller
{
public function __construct(){
parent::__construct();
$this->load->library('session');
}
public function index() {
print_r($this->session->userdata('username'));
}
}
我还有自动加载会话:
$autoload['libraries'] = array('database','session','form_validation', 'pagination', 'user_agent','encryption');
【问题讨论】:
-
如果您已经在自动加载会话库,则无需在每个控制器上加载会话库。话虽如此,
print_r之前需要一个echo或print声明......你试过print print_r($this->session->userdata('username'));吗? -
避免在控制器中加载会话库。使用 config.php 中定义的自动加载数组
-
@JavierLarroulet:我尝试从其他控制器中删除会话,即仅从自动加载加载会话,并尝试回显或打印,但仍然在会话中显示空结果。
-
@Riosant:删除了控制器中的加载会话库,但结果仍然相同。
标签: php mysql codeigniter session codeigniter-3