Tuesday, 12 June 2012

Session expiry in CodeIgniter


Though the CodeIgniter 2.1.0 has included a new feature in Session class to define the session expiry on browser with the help of a configuration in the config.
$config['sess_expire_on_close'TRUE
it is not available there in CodeIgniter 1.7.2 and for some reason the session doesn’t expire automatically on browser close in this version. Though the ideal way would of course be to upgrade the version to CodeIgniter 2.1.0 still for people like me for whom an immediate upgrade in their live projects is not possible the following could work as a quick fix.
1. Add a variable to the Session class in CodeIgniter\system\libraries\Session.php as below:
var $sess_expire_on_close = FALSE
2. In that same Session class, in the function declared as _set_cookie($cookie_data = NULL) update the below mentioned lines
setcookie(
    
$this->sess_cookie_name,
    
$cookie_data,
    
$expire,
    
$this->cookie_path,
    
$this->cookie_domain); 
to
$expire =($this->sess_expire_on_close===TRUE)?0:$this->sess_expiration+time();
  
setcookie(
      
$this->sess_cookie_name,
      
$cookie_data,
      
$expire,
      
$this->cookie_path,
      
$this->cookie_domain); 
3. Again in the Session class in the constructor CI_Session change
 foreach (array('sess_encrypt_cookie''sess_use_database''sess_table_name',   
  'sess_expiration''sess_match_ip''sess_match_useragent''sess_cookie_name'
  'cookie_path''cookie_domain''sess_time_to_update''time_reference'
  'cookie_prefix''encryption_key') as $key)
 {
 $this
->$key =(isset($params[$key]))?$params[$key]:$this->CI->config->item($key);
 
   to
  foreach(array('sess_encrypt_cookie''sess_use_database''sess_table_name',
 'sess_expiration''sess_match_ip''sess_match_useragent''sess_cookie_name',
 'cookie_path''cookie_domain''sess_time_to_update''time_reference'
'cookie_prefix''encryption_key' 'sess_expire_on_close' ) as $key)
 
{
  $this
->$key=(isset($params[$key]))?$params[$key]:$this->CI->config->item($key);
 
4. Now in Config.php in add the following line
 $config['sess_expire_on_close'TRUE;
These four steps should do the trick in CodeIgniter 1.7.2 and the sessions should be expiring on browser close automatically by now.

2 comments:

  1. I am using latest version 2.1.3 but $config['sess_expire_on_close'] = TRUE; does not work, i have searched a lot on net but can't find solution. please help me

    ReplyDelete
  2. Hi Azam Alvi,
    Session expiry not working in CI 2.1.3 is strange. You may try the solution I have used for CI 1.7 as above. However I have not tried it with CI 2.1.3 yet.

    ReplyDelete