Session is not working out when redirecting from one controller to another. In below example, I am simply trying to check login and if valid user then set username to session from the Controller named "Login" and redirect to another controller "Testing" and print the session value. But, When the user is validated, session works fine till we are in Login controller (I checked by putting print_r($this->session->userdata('username')); by removing redirect method) and when I redirect, the session value shows empty from redirected Controller.
Here is the sample of my code:
Controller: 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');
}
}
Model: 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();
}
}
Controller: 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'));
}
}
Also I have autoload session:
$autoload['libraries'] = array('database','session','form_validation', 'pagination', 'user_agent','encryption');
print_rneeds anechoorprintstatement before it... Have you triedprint print_r($this->session->userdata('username'));? - Javier Larroulet