Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter Session Data not working

I'm creating a session at login but it's not saving the variables I store inside the session nor is it carrying them across to other pages:

Controller code:

    function CheckDatabase($password) //This function is only run when password validation is correct.//
{
    $username = $this->input->post('Username'); //Sets the username as a $username.//
    $result = $this->User_model->Login($username, $password);

    if($result)
    {
        $sess_array = array();
        foreach($result as $row)
        {
            $sess_array = array( //Makes an array of the data to be stored in the session.//
            'UserID' => $row->UserID,
            'Username' => $row->Username
            );

            $this->session->set_userdata('logged_in', $sess_array); //Sets $sess_array as the session.//
        }

        return TRUE;
   }

    else //Ran if the username or password aren't matched in the CIUsers database. Returns error message.//
    {
        $this->form_validation->set_message('CheckDatabase', 'Invalid login details.');
        return false;
    }
}

Index function on the same controller (which should stop a user going back to the login screen but doesn't)

    function index() //Default function that is run when this controller is called.//
{

    if($this->session->userdata('logged_in'))
    {
        redirect('Home_controller');
    }

    else
    {
        $this->load->helper(array('form'));
        $this->load->view('Login_view');
    }

}

Code on the home view (which browser is directed to once logged in)

<?php echo $UserID .": ".$Username; ?>

I get this error for displaying the session data:

Message: Undefined variable: Username

Filename: views/Home_view.php

Line Number: 9

like image 943
user3574766 Avatar asked Aug 16 '26 09:08

user3574766


1 Answers

To retrieve the session variable, you have to do like this

 $username = $this->session->userdata['logged_in']['Username'];
 echo $username;
like image 156
Yuva Raj Avatar answered Aug 18 '26 22:08

Yuva Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!