Parker
Parker

Reputation: 141

how to keep the session alive after browser closed in codeigniter?

I know that we can do using php ini settings. by set the session cookie life time increase. But how to do it in codeigniter without the php ini settings.

my config file

$config['sess_driver'] = 'database';
$config['sess_use_database'] = TRUE;
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 60 * 60 * 24 * 180;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 0;
$config['sess_regenerate_destroy'] = FALSE;

Upvotes: 1

Views: 2444

Answers (2)

Parker
Parker

Reputation: 141

first step is create a token field in databse for that userid and when we create session for the first time for the user set cookie token an dupdate in databse. and then everytime on login check that user cookie from browser and check with the database token matched and start the session for the user. Please check wiht my below code

$values = array(
                'user_id' => $row->id,
                'logged_in' => TRUE,
                'role' => $row->role_id,
                'email' =>$row->email
            );
     $this->session->set_userdata($values);

     $cookie = array(
        'name' => 'token',
        'value' => generateRandomString() ,
        'expire' => '1209600',
        'domain' => domain() ,
        'path' => '/'
    );

    set_cookie($cookie);

    $update = array(
        'token' => $cookie['value'],
    );

    $this->db->where('id', $row->id);
    $this->db->update('user', $update);


   if ($CI->session->userdata('logged_in')==1 &&                                           $CI->session->userdata('user_id')) {
        $query = $CI->db->query("select * from user where token= '".$token."' and role_id=2");
        $result = $query->row();
        if($result->token==$token){

             $values = array(
                    'user_id' => $result->id,
                    'logged_in' => TRUE,
                    'role' => $result->role_id,
                    'email' =>$result->email
                );

            $CI->session->set_userdata($values);

Upvotes: 1

Denis K.
Denis K.

Reputation: 11

You would enable session by IP.

$config['sess_match_ip'] = TRUE;

So if you close your browser and open it again, codeigniter CI Session would detect same IP and reestablish session. Works only if you open the site is opened by the same PC and the IP has not changed meanwhile.

Upvotes: 0

Related Questions