CodeIgniter: storing sessions in DB, how to know who session came from?
I'm thinking of storing CI sessions in the database so I can display how many users are currently online, who specifically is online, etc.
Looking at http://codeigniter.com/user_guide/libraries/sessions.开发者_运维百科html, am I right in my understanding that information would be stored in the user_data
column of the ci_session
table? Meaning, maybe I just store the user's id in there?
CodeIgniter will store the data in the table you specify in your config file. By default, it's ci_session
. The session information, what is accessible through $_SESSION
for instance, is serialized and saved in a column named user_data
. That field will not be able to tell you whether or not the session has expired (or in other words, how many people are online).
What you could do instead is use the last_activity
column, which is a timestamp of the last time that session was active. You could run a SQL query that selects the count of session_id
where the last_activity
is less than 2 minutes ago.
SELECT COUNT(`session_id`) AS `active_user_count` FROM `ci_session` WHERE `last_activity` >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE)
With that said, an existing session doesn't necessarily mean that the user is "signed in". If you need to check that they're signed in, you can use a LIKE
operator to add a condition to the WHERE
statement that checks if a user is signed in. This will depend on what variable name you're using so have a look at your data and see if you can figure it out.
For example:
SELECT COUNT(`session_id`) AS `active_user_count` FROM `ci_session` WHERE `last_activity` >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE) AND `user_data` LIKE '%s:9:"logged_in";b:1;%'
This works! use it
$session = $this->db->get('ci_sessions')->result_array();
foreach ($session as $sessions) {
$sessio = $sessions['last_activity'] + 7200;
echo $sessio . "time";
echo now();
echo "||";
$custom_data = $this->session->_unserialize($sessions['user_data']);
if (is_array($custom_data)) {
foreach ($custom_data as $key => $val) {
$user[$key] = $val;
}
}
}
print_r($user);
exit();`
精彩评论