Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 17 revisions

CI_Session extension that includes a method to remove session cookie when browse closes.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * MY_Session Class
 */
class MY_Session extends CI_Session {
    
    var $close;

    /**
     * Overwrite _set_cookie
     */
    function _set_cookie($cookie_data = NULL)
    {
        if (is_null($cookie_data))
        {
            $cookie_data = $this->userdata;
        }

        // Serialize the userdata for the cookie
        $cookie_data = $this->_serialize($cookie_data);

        if ($this->sess_encrypt_cookie == TRUE)
        {
            $cookie_data = $this->CI->encrypt->encode($cookie_data);
        }
        else
        {
            // if encryption is not used, we provide an md5 hash to prevent userside tampering
            $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
        }

        // Set the cookie
        setcookie(
                    $this->sess_cookie_name,
                    $cookie_data,
                    $this->close ? 0 : $this->sess_expiration + time(),
                    $this->cookie_path,
                    $this->cookie_domain,
                    0
                );
    }
    
    
    /**
     * Cookie will only last till browser is close
     */
    function expire_cookie($bool) 
    {
        $this->close = $bool;
        $this->sess_time_to_update = -1;
        $this->sess_update();
    }
    
}

== What this does: ==

  • Extends CI_Session -- Adds new variable 'close'. -- Overwrites the '_set_cookie' method. -- Creates new function 'expired_cookie'

== How to use: ==

Put MY_Session.php in your system\application\libraries folder

Call $this->session->expire_cookie(true); when cookie should be removed when browser close

Call $this->session->expire_cookie(false); when cookie should last as long as $this->config->item('sess_expiration')

== Example: ==

  1. In your view include a input[type=checkbox]

<input type="checkbox" name="remember_me" id="remember" value="true" />

  1. In your controller

if (!$this->input->post('sign_in_remember')) { $this->CI->session->expire_cookie(true); }

The session cookie which CI_Session creates always last between 1 sec to 2 years by default depending on what you set you config.php sess_expiration to.

So if user checks "remember_me" you should make sess_expiration last "forever" (which is actually 2 years)

And if the user doesn't check "remember_me" run the "expire_cookie(true)" method to make the cookie die on browser close

Sorry for my bad english. Someone can clean it up.

Regards, PK

Clone this wiki locally