-
Notifications
You must be signed in to change notification settings - Fork 26
PK 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 */ 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(); }
-
} [/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.