Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session variable in Codeigniter Not Working

Hi i have created a session in Codeigniter i have set the session variable in my model. But after setting the session variable value when i call session variable in my view through Controller the session variable value becomes null. Any help???

Update

This is my Model where i set my session variable

function login ($username, $password)

    {
        $this->db->where('username' , $username);
        $this->db->where('password', $password);

        $query = $this->db->get('users');

        if ($query->num_rows()>0)

        {
            foreach ($query->result() as $rows)
            {
                $data = array(

                    'user_name' => $rows->username,
                    'logged_in' => TRUE,
                    'validated' => true
                );
            }

                $this->session->set_userdata($data);
                //$user = $rows->username;
                //$this->session->set_userdata('user_name', $user);

                return true;
        }

        else

        {
            return false;
        }

    }

Here is my controller from where i redirect to the view

public function verification()

    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');


        $result = $this->site_model->login($username, $password);


        //$result = $this->session->set_userdata('validated');

        if ($result)
        {
            //$this->admin();
            //$this->session->set_userdata('login_state', TRUE);

            redirect ('site/index');

        }
        else
        {

            redirect ('site/login');
            //$this->load->view('login');
        }
    }

i have called the session_start(); in controller under construct();

and this is how i access the session variable in my view

<?php if ($this->session->userdata('user_name') != "") { ?>

.....
like image 599
Abbasi Avatar asked Aug 27 '13 06:08

Abbasi


1 Answers

First of All in CI you don't need to use session_start() anywhere. only autoload session in config/autoload.php file.

Remove that session_start(). Try to use flashdata. Flashdata is temporary session mostly used in your type of case where We need to redirect user to another page and display some success or error message.

  1. Set flashdata: $this->session->set_flashdata('item', 'value');

  2. get flashdata: $this->session->flashdata('item');

Here is the documentation link http://www.codeigniter.com/user_guide/libraries/sessions.html#flashdata

like image 182
Farman Memon Avatar answered Nov 05 '22 05:11

Farman Memon