beNerd
beNerd

Reputation: 3374

Cannot access $_SESSION variable in codeigniter controller

I am having a controller for verifying the user as follows:

function index()
{
    if($this->input->post('username'))
    {
        $username=$this->input->post('username');
        $password=$this->input->post('password');
        $this->mstudents->verifyUser($username,$password);
        if(@$_SESSION['sutdentUsername']!=""){
        echo "success";
        }
        else
        {
            echo "error";
        }
    }
    else
    {
        echo "error";
    }

}

This function is called by ajax in a view as follows:

$.post('<?PHP echo base_url();?>account/login/',{username:$("#username").val(),password:$("#password").val()},function(data){

        $("#loginButton").button('reset');
        if(data=="success")
        {
            window.location="<?PHP echo base_url();?>account/dashboard";
        }
        });

Now the problem is that when i try to access the session variable in dashboard for validation, it gets a blank $_SESSION array. What could be the problem?

This is my modal code for verifUser:

function verifyUser($username,$password)
{
    $data=array();
    $this->db->where('email',$username);
    $this->db->where('password',$password);
    $this->db->where('status','active');
    $Q=$this->db->get('students');
    if($Q->num_rows()>0)
    {
        $row=$Q->row_array();       
        $_SESSION['sutdentUsername']=$row['email'];

    }
    else
    {
        $_SESSION['sutdentUsername']="";
    }
}

I have this code in code in the constructor of the all the controllers:

function __construct()
{
    parent::__construct();
    session_start();
    print_r($_SESSION);

The directory structure for controllers is like:

CONTROLLERS: account -dashboard -login other controllers goes here...

Upvotes: 1

Views: 2035

Answers (2)

Nerdroid
Nerdroid

Reputation: 13966

because you are using native php session you need to start the session first using session_start(); place it inside index.php or you can place it in your __construct()

Upvotes: 3

sandip
sandip

Reputation: 3289

From my understanding may be you should try this:

Depending if you auto-load the session library or not, we will need to include:

$this->load->library('session');

Then you should be able to use:

$this->session->set_userdata('some_name', 'some_value');

$session_id = $this->session->userdata('some_name');

I hope this is the same what you need.

Upvotes: 4

Related Questions