简体   繁体   中英

Session Data Lost after redirecting to another controller in Codeigniter

I m using CodeIgniter framework and I was unable to maintain session data while redirecting from one controller to another . here is my first controller where I set session data

//Ajax login function 
function ajax_login() {
$response = array();

//Recieving post input of email, password from ajax request
$email = $_POST["email"];
$password = $_POST["password"];
$response['submitted_data'] = $_POST;

//Validating login
$login_status = $this->validate_login($email, $password);
$response['login_status'] = $login_status;
if ($login_status == 'success') {

redirect(base_url() . 'index.php?admin/dashboard', 'refresh'); 
}


//Replying ajax request with validation response
echo json_encode($response);
}

//Validating login from ajax request
function validate_login($email = '', $password = '') {
$credential = array('email' => $email, 'password' => $password);

// Checking login credential for admin
$query = $this->db->get_where('admin', $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('admin_login', '1');
$this->session->set_userdata('admin_id', $row->admin_id);
$this->session->set_userdata('login_user_id', $row->admin_id);
$this->session->set_userdata('name', $row->name);
$this->session->set_userdata('login_type', 'admin');   
return 'success';
}

so when i vardump($this->session->userdata()) i get a all the data stored above and the redirected controller is

function dashboard()
{
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
$page_data['page_name'] = 'dashboard';
$page_data['page_title'] = get_phrase('admin_dashboard');
$this->load->view('backend/index', $page_data);
}

at second controller I m getting an empty user data array

NOTE: I already loaded session library in _construct() of both controllers that is

function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library('session');

/*cache control*/
$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
$this->output->set_header('Pragma: no-cache');

}

so whern i vardump($this->session->userdata()) i get a NULL

Load database and session library from autoload.php file

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

Then you wouldn't need to add these twos' in every constructor. It will generate a unique session for the app. Give it a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM