I have a user controller that checks to login a user. It has this snippet of code. I can set set_userdata and echo it in my view, but this doesnt work for my flash data as shown below.
public function login()
{
if($this->input->post('submit_login'))
{
// Get Posted Vars
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
// Run query to return 1 result if TRUE
$query = $this->user_model->check_login($username, $password);
if ($query == FALSE)
{
$this->session->set_flashdata('flashdata', 'Incorrect Username or Password doesnt show');
$this->session->set_userdata('userdata', 'userdata works');
// Query was wrong, set flash data and redirect to login
$data['main_content'] = "user/login";
$data['title'] = "Login";
$this->load->view('template', $data);
}
else // Else Query returned 1 item
{
// Get the Variables
$user_id = $query->row(0)->id;
$username = $query->row(0)->username;
$user_email = $query->row(0)->email;
$user_type = $query->row(0)->type;
// Load up the userdata array
$userdata = array(
'logged_in' => TRUE,
'user_id' => $user_id,
'username' => $username,
'user_email' => $user_email,
'user_type' => $user_type
);
// Execute the set_userdata, to our session
$this->session->set_userdata($userdata);
$data['main_content'] = "Admin/index";
$data['title'] = "Administrator";
$this->load->view('template', $data);
}
}
elseif ($this->session->userdata('logged_in') == TRUE)
{
$this->index();
}
else
{
$data['main_content'] = "user/login";
$data['title'] = "Login";
$this->load->view('template', $data);
}
Then in my view:
<form action="<?php echo base_url(); ?>user/login" method="POST" id="login_form"/>
<p>Please Login Below</p>
<span class="notice"><?php echo $this->session->flashdata('flashdata'); ?></span>
<span class="label">Username:</span><input type="text" name="username"/><br/>
<span class="label">Password:</span><input type="password" name="password"/><br/>
<input type="submit" name="submit_login" value="Login"/>
</form>
<?php echo $this->session->flashdata('flashdata'); ?>
<br/>
<?php echo $this->session->userdata('userdata'); ?>
Why doesnt flashdata show?
flashdatain codeigniter only exists in the session for one additional request and then is destroyed. If you are inadvertently trying to use it past a single request, it will not exist by the time you try and access it.userdatathough exists as long as the session exists.UPDATE
After looking at more of your code, it looks like this happens because you’re not actually redirecting (creating the next request) here, you’re just loading a view…
Instead do this…