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

Category:Libraries::Session

A MY_Session that includes a method to remove session cookie when browse closes.

  • Create MY_Session.php in your system\application\libraries folder and paste the following code. [code] <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /**

  • MY_Session Class

  • Extends the core CI_Session giving it the ability to create

  • session cookies that expire when the browser closes */ class MY_Session extends CI_Session {

    var $close;

    /**

    • Overwrites the core CI_Session _set_cookie function */ 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, // determine if session cookie expires on browser close $this->close ? 0 : $this->sess_expiration + time(), $this->cookie_path, $this->cookie_domain, 0 ); }

    /**

    • New function to toggle between a session cookie that
    • expires on browser close and one that doesn't */ function expire_cookie($bool) { $this->close = $bool; $this->sess_time_to_update = -1; $this->sess_update(); }

} [/code]

[h3]How to use[/h3]

  • 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')

[h3]Example[/h3]

  • In your view, create a input[type="checkbox"]

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

  • In your controller, call expire_cookie

[code] if ($this->input->post('remember_me')) { $this->session->expire_cookie(false); } else { $this->session->expire_cookie(true); } [/code]

[h3]How it works[/h3] The session cookie which CI_Session creates last between 1-63072000 sec depending on your config.php $config['sess_expiration'] setting.

If the user checks "remember_me" the session cookie should last 'forever' (for 2 years). If the user doesn't check "remember_me" call "expire_cookie(true)" to make the cookie last only till the end of the browser session.

Clone this wiki locally