Find total logged in time of users in codeigniter - php

I have to prepare a report in codeigniter of the login and logout time of users. I have overridden the session library and changed the function of set_userdata according to it.
My problem is when user doesn't select the logout button, or if he/she is logged in simultaneously from more then one system; in that case how can I keep a log of login and logout time?
I added the following code to the session_destroy function of the session library
$session_id=$this->userdata['session_id'];
$c_array=array('logout_time'=>date('Y-m-d H:i:s'));
$this->CI->db->where('session_id',$session_id);
$this->CI->db->update('login_activities',$c_array);
but the session_id changed after some time in the ci_session table

we cant always get the logout time, because if the user close the browser there won't be able to add a logout time, in the case of normal logout its ok..
here my suggession is:
instead of logout_time we need current_time and a usage field
if the user is logged an ajax is run on page for every second or (may be in 3 seconds or 5)
at every time the ajax runs: the current_time updated with the current time stamp, and the usage field must be updated with time in seconds that can be calculated by difference in login_time and current time
use the following function:
function getTimeInSec($t1, $t2)
{
$timeFirst = strtotime($t1);
$timeSecond = strtotime($t2);
$differenceInSeconds = $timeSecond - $timeFirst;
return $differenceInSeconds;
}
here $t1 is the current_time and $t2 is the login_time....
(both ar in format 'Y-m-d H:i:s')
script for ajax call:
<script>
jQuery(document).ready(function($){
getRefresh(1000);
});
function getHeader()
{
$.post("<?php echo site_url('mycontroller/refreshAjax');?>", {
},
function(response)
{
});
}
function getRefresh(tim)
{
getHeader();
setTimeout("getRefresh("+tim+")", tim);
}
</script>
in the controller function refreshAjax() there must be update query for the table to update...

Related

session timeout due to inactivity + alert box

i am looking for solution of my answer which is half completed i have to make the user logout from my website and i used your solution which is as follow:-
if( $_SESSION['last_activity'] < time()-$_SESSION['expire_time'] ) {
//have we expired?
//redirect to logout.php
header('Location: '.BASE_FULL_PATH.'/user/logout'); //change yoursite.com to the name of you site!!
} else{ //if we haven't expired:
$_SESSION['last_activity'] = time(); //this was the moment of last activity.
}
$_SESSION['logged_in'] = true;
$_SESSION['last_activity'] = time();
$_SESSION['expire_time'] = 24*60*60;
and it is working perfectly but i need to have an alert box when the session is about to expire.Try lot of stuff but doesn't help.Please reply and thanks for your brilliant demo
I know , this is not an efficient way, But you can try this.
try ajax, that runs a php file in server every 5 or 10 second time gap.
that ajax running php file contains session last_activity and expire_time comparing code,
<?php
$warning=100;
if( $_SESSION['last_activity']+warning < time()-$_SESSION['expire_time'] ) {
?>
<script type="text/javascript">
alert("Your session will expire soon!");
</script>
<?php
}
?>
You can set the variable $warning to adjust the alert message time.
Since your session expiry will reset every time you reload the page, then you can use the expiry time as the time argument of JavaScript's setTimeout() function.
var sessionExpiryTime = 24 * 60 * 60;
var sessionExpiryAlertTime = sessionExpiryTime - 5; //assuming we want the alert to show 5 seconds before expiry
setTimeout(function({
alert("Session about to expire!");
}, sessionExpiryAlertTime * 1000); //time is in milliseconds so we multiply by 1000
This works okay as long as the user has JavaScript enabled. If the user reloads the page, the expiry timer updates as per your php code and the setTimeout() function restarts.

how to auto log out if user is inactive for some specific duration using codeigniter

If user is inactive for some specific duration, then it should autometically log out. So how I can do this using codeigniter?
OR
how to check whether user is active or not after login on that site?
// Add the following into your HEAD section
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 10000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
window.location = "your_logout_script.php";
}
// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"
You can save the time that your user logged-in in a session or a cookie
Example: $this->session->set_userdata('time', time());
and use a javascriptjQuery function (Exp. $.getJSON('time.php', function (data) {alert(data.serverTime);});) or anything else to check the current time. Then, log your user out when needed.
However, next time, please place code or something else that shows your efforts.
<?php
$minutes=3;//Set logout time in minutes
if (!isset($_SESSION['time'])) {
$_SESSION['time'] = time();
} else if (time() – $_SESSION['time'] > $minutes*60) {
session_destroy();
header(‘location:login.php’);//redirect user to a login page or any page to which we want to redirect.
}
?>
... which was originally taken from skillrow.com/log-out-user-if-user-is-inactive-for-certain-time-php/ (now 404).

How to count time from when user load a page/form until they submit it?

I have a quiz page with some questions (multiple choice, true-false). In the results after the submit of page i want to show something like this:
Started on Tuesday, 1 January 2013, 04:09 AM
Completed on Tuesday, 1 January 2013, 04:10 AM
Time taken 47 secs
Grade 7 out of a maximum of 10 (65%)
i dont know how to count start time and end time to show the above results and how to count the time from when user's load a page until they submit the form.
i'm new and i need your advise. i dont have problem if the problem solved with php or javascript or jquery
You can do something like this and the start and end timestamps will be submitted along with the form. You could then do the calculations with PHP.
var form = document.getElementById("form");
window.onload = function() {
var start = document.createElement("input");
start.type = "hidden";
start.name = "start";
start.value = +new Date()/1000; //unix timestamp
form.appendChild(start);
};
form.onsubmit = function() {
var stop = document.createElement("input");
stop.type = "hidden";
stop.name = "stop";
stop.value = +new Date()/1000;
form.appendChild(stop);
};
Ok here is my solution:
1- user starts the quiz and you put the time in $_SESSION var
$_SESSION['quiztime']=date("Y-m-d H:i:s");
2-User finishes the test and you check the time passed (this example is in minutes you don't have to divide it by 60 if you need seconds)
$to_time = strtotime(date("Y-m-d H:i:s"));
$from_time = strtotime($_SESSION['quiztime']);
echo round(abs($to_time - $from_time) / 60,2). " minutes";
I'd put the time started in a cookie or session, and then once they complete it, just subtract that time from the current time -- That's the time taken!
It may look like this:
Quiz page:
session_start();
$_SESSION['startTime'] = time();
// This is where the quiz would be displayed
Quiz results page:
session_start();
$totalTime = time() - $_SESSION['startTime'];
echo $totalTime;
My "bullet-proofer" solution would be to store the start time on the server, (in the session) associated with a unique id generated per-form and kept in an hidden field.
This way you prevent the user from tampering with it (he might change the unique id, but in that case the form would be invalid) and you don't depend on the client having javascript enabled.
<?php
$form_uuid = uniqid();
$_SESSION['quiz_start_time'][$form_uuid] = time();
Then, in your form, put something like this:
<input type="hidden" name="form_id" value="<?php print $form_uuid; ?>">
And in the form submit handler:
<?php
$form_uuid = $_POST['form_id'];
if (!isset($_SESSION['quiz_start_time'][$form_uuid])) {
// The user is trying to do something nasty (or the session just expired)
// Return something like a 400 error
}
else {
$start_time = $_SESSION['quiz_start_time'][$form_uuid];
// Do other form processing here..
}

php session every 24 hours to be cleaned

I want one session variable to be cleaned every 24 hours .I don't want to kill or unset all the sessions just one session to be unset every 24 hours a day.
When the session is 1st created on the client just give it a date:
if(!isset($_SESSION['date'])
$_SESSION['date'] = date('m_d_y');
Then whenever the page changes check that date:
if($_SESSION['date'] == date('m_d_y')){
//still today
}
else {
//destroy session
}
Or you could do it with timestamp and check based on the number of hours:
if(!isset($_SESSION['creationTime'])
$_SESSION['creationTime'] = time();
if (time() - $_SESSION['creationTime'] <= 60*60*24 ){
//still today
}
else {
//destroy session
}
try to set Cookie expired time into now() + 24 hours...
When you creating session, write to it timestamp. Then you are using seesion check the actually timestamp and of creating session, then if difference is grather than 86400, then drop session and create new one.
This solution prevent users from using sessions older than 24hours. You can apply other comparing algorithm to eg. prevent users from using session before 1AM of current day. Then will be work exaclly same when you will want erase session every 24hours in 1AM every day.
When create session (maybe when user login), declare session timeout:
session_start();
$_SESSION["timeout"] = time()+ (60*60*24);
Create backend function / page where jquery can call every 10 seconds / 5 seconds up to you (I save it as get_session.php):
session_start();
$session_life = time() - $_SESSION["timeout"];
$inactive = 0;
if($session_life > $inactive){
session_destroy();
echo 'Destroyed';
}
The jquery script run every 5 second (recommended at master page / template header / footer of the page):
<script type="text/javascript">
window.setInterval(function(){
sessionHeartBeat();
}, 5000);
function sessionHeartBeat(){
$.ajax({
url: 'get_session.php',
success: function(response){
console.log(response);
}
});
}
</script>

Force Logout users if users are inactive for a certain period of time

Assume that you are doing a banking application. If users are logged into your site, how to detect their inactivity and ask them to log out if they remain inactive for a period of time? Inactive here means they have either switch to other tabs, or not touching the browser application.
I guess think I can do this by registering every mouse movement or keyboard movement when users are doing on EVERY page of my application. But the code would be very ugly and hard to maintain. Is there other more elegant ways of doing this?
This is the code I use. It is not mine, but I did modify it to it's 'perfection'.
// Add the following into your HEAD section
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 10000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
window.location = "your_logout_script.php";
}
// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"
Good luck.
If the user is requesting new pages/data from your server on a regular basis, then adjusting the session timeout in PHP should work for this (assuming you are using PHP sessions).
If the concern is that they could be sitting on one page for a good length of time with no trips to the server (e.g. filling out a long form), and you want to distinguish between this and the user simply switching to another window, you could do something like use javascript to request some data using XMLHTTPRequest every five minutes or so to keep the session alive. You could use the window.focus and window.onblur events in javascript to stop and restart this mechanism (I think there are some differences for IE, there is a good explanation here).
A very easy and effective way of doing this is by placing something like this in your HTML HEAD section:
<META HTTP-EQUIV="refresh" CONTENT="1800;URL=logout.php?timeout">
Replace the logout.php?timeout with the appropriate script .. In the example above, if ?timeout is in the query string, I show them a login page with information indicating that they've been logged out due to inactivity.
Replace 1800 with the time in seconds that you wish to allow them to stay inactive before automatically logging them out. Set this to the same time that you have your session expiration set to.
Edit - Another easy mechanism to implement is to have a session variable called last_time, or last_activity, or something along those lines, and set it to a timestamp everytime there is activity. In most of my stuff, I have a general include file that I do this in. In the same file, you could check to ensure that it's within the constraints that you've set forth for an active session. If it's been too long -- just do a 300 redirect to the logout page and display the appropriate inactivity message there.
Good luck!
Ian
We can improve our codes to jquery now
idleTime = 0;
$(document).ready(function() {
var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute //60000
$(this).mousemove(function(e) {
idleTime = 0;
});
$(this).keypress(function(e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 5) {
window.location = $('#base_url').val() + 'home/logout_user';
}
}
You can do it more elegantly with underscore and jquery javascript libraries-
$('body').on("click mousemove keyup", _.debounce(function(){
// logout user here
}, 1800000)) // 30 minutes inactivity
It depends how they are "logged in" in the first place. Doesn't the session expiration on the server do this for you? If you really want to do it manually then you could use some javascript in a setTimeout, but thats ugly
Usually the session lifetime is used to determine whether a user is logged in or not. So you could set a flag in the session that represents this state. And if it’s missing (either the user didn’t log in yet or the session timed out), he is considered as not logged in.
You can have a bit of javascript that checks the server every x minutes to see when the user's last activity was. Shouldn't be more than a few lines of code. I would also add a meta refresh if the user has javascript disabled.
I took the timestamp 'now' and check on each click if the delay is less than 3000 seconds or more than billions of seconds, which means that the user just logged in, if it's not it will redirect to logout
var time = 0;
$(document).on('click', function() {
var now = Date.now() / 1000 | 0;
if (now - time < 3000 || now - time > 1480000000) {
time = now;
} else {
window.location.replace("http://url");
}
})
put in header of your java script page.. if you want to avoid the backend calls
Below is the snip-let under script tag :
<script>
var idleTime = 0;
function func(){
console.log(idleTime);
$(this).keypress(function(e) {
idleTime = 0;
});
$(this).click(function(e) {
idleTime = 0;
});
timerIncrement();
}
function timerIncrement() {
console.log("timerIncrement");
console.log(idleTime);
idleTime = idleTime + 1;
if (idleTime >= 1) {
console.log(window.location);
logoutcall(); //API call
window.location = window.location.origin+"/riskoffice_UI/Login";
}
}
setInterval(func,1800000) //Runs the "func" function every second
</script>
Update : localStorage can be use to keep idle time for the application with multiple tabs are opened.
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store an item to localStorage
localStorage.setItem("timeIdle", "0");
console.log(localStorage.getItem("idleTime"));
// Retrieve the added item
} else {
//display this message if browser does not support localStorage
console.log("Sorry, your browser does not support Web Storage.");
}
function func(){
$(this).keypress(function(e) {
localStorage.setItem("timeIdle", "0");
});
$(this).click(function(e) {
localStorage.setItem("timeIdle", "0");
});
timerIncrement();
}
function timerIncrement() {
var timeIdle = localStorage.getItem("timeIdle");
timeIdle = parseInt(timeIdle) + 1;
if (timeIdle >= 1) {
logoutCall();
window.location = window.location.origin+"/riskoffice-ui/Login";
}
localStorage.setItem("timeIdle", timeIdle.toString());
}
setInterval(func,1800000); //Runs the "func" function every second

Categories