Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter - Session expiration and "remember me" feature

I'm building a "Remember Me" feature in Codeigniter, normally I see libraries/projects setting a cookie on the user with a token, this token gets saved in the database and is compared each time the user accesses the website.

In Codeigniter we can set the session expiration time though, this lead me to try a different approach, this is what I did:

  • I set the session_expiration in config to 0 (infinite session)
  • If the user leaves "Remember me" unchecked, I set a 2 hour time in the session and session destroy on window close.

So my login code looks like this:

if (!$this->input->post('remember_me')) {
                $this->session->sess_expiration = 7200;
                $this->session->sess_expire_on_close = TRUE;
            }

            $this->session->set_userdata($session_data);

And my config file:

$config['sess_expiration']      = 0;
$config['sess_expire_on_close'] = FALSE;

I don't see people using this solution on projects, I have tested this out and it seems to work fine though.

SO, for my question, would you say this a safe practice to do? Any security dangers I should know about? Any input on this solution vs cookie+database token would be great.

like image 414
Jorg Ancrath Avatar asked Jan 27 '13 17:01

Jorg Ancrath


2 Answers

The simpliest solution that I have found for this problem is to just modify the cookie created by Codeigniter by this way:

        $this->session->set_userdata('user', $user); // a cookie has been created
        if($this->input->post('remember_me'))
        {
            $this->load->helper('cookie');
            $cookie = $this->input->cookie('ci_session'); // we get the cookie
            $this->input->set_cookie('ci_session', $cookie, '35580000'); // and add one year to it's expiration
        }
like image 131
ramz Avatar answered Sep 20 '22 06:09

ramz


Also this can be done by editing/extending system Session library.

First: Set regular session expire time in config file. Second: In user login function add remember me check-

    if($remember)
    {
        $data['new_expiration'] = 60*60*24*30;//30 days
        $this->session->sess_expiration = $data['new_expiration'];
    }
    $this->session->set_userdata($data);

Third: Edit system Session library [I am not sure whether extending Session will work or not] Go to this line in sess_read() method

if (($session['last_activity'] + $this->sess_expiration) < $this->now)

Before that line add following code

if(isset($session['new_expiration'])){
   $this->sess_expiration = $session['new_expiration'];
}

This works fine for me.

like image 45
Sadat Avatar answered Sep 22 '22 06:09

Sadat