Sessions in Codeigniter are good for everyone. True, very conveniently made, especially when you store sessions in the database (which I think is the only correct one). Cookies are encrypted, there is nothing in cookies but an identifier. They are bound to user_agent and, optionally, to IP. Beautiful, safe.
But they have a very significant drawback: the life of the session is considered to be from the
last_activity field. This means that if you have an expire session in two days, then when you refer to a session that has last_activity <time () - 172800, it is eliminated and a new one begins. Consequently, in order that users do not have to log in to the site each time, last_activity must be maintained in an up-to-date state.
The last_activity field is updated in two cases: when you write something new to the session, or when the session is updated (by default, every 5 minutes, again, relative to the last_activity; indicated in the config file). And the main problem is that when the session
is updated, the
session_id changes and the current session of the user is interrupted, a new one starts.
Frankly, such behavior of the sessions led me to a state of ... surprise. In such a reality, using native sessions as a tool to support authorization seems impossible ...
')
The problem is “burning”, it is often remembered on the Codeigniter forums, but I haven’t seen a sensible solution anywhere.
But ashes, as you know, is cunning to fabrications, so there was a simple solution.
The first thing to do is to specify in the
config / config.php how often the session is updated equal to the time of its expire:
================
$config['sess_time_to_update'] = $config['sess_expiration'];
================
Then, enable the
hooks :
================
$config['enable_hooks'] = TRUE;
================
Then, in
config / hooks.php :
================
$hook['post_controller_constructor'] = array(
'class' => '',
'function' => 'sess_update',
'filename' => 'sess_update.php',
'filepath' => 'hooks'
);
================
(the point of the hook can, in principle, be any, the main thing is that it be executed each time the page is opened)
And in the hooks create
sess_update.php :
================
<?php
function sess_update()
{
$CI =& get_instance();
if ($CI->session->userdata('last_activity')< time() - 300) {
$CI->session->set_userdata('last_activity', time());
}
}
================
The function is as simple as 5 kopecks: we get a link to the codeigniter superobject, see if 5 minutes has passed since the session was last updated (so as not to storm the database with unnecessary requests each time) and, if passed, manually set the last_activity field to the current time .
In fact, it’s the same effect as specifying 5 minutes in $ config ['sess_time_to_update'], but the session itself remains intact, the data does not disappear and, your authorized user, came to the site the next day, or after two ( depending on the value of $ config ['sess_expiration']) will remain authorized.