PHP + MYSQL, Need to update logout time in DB every n minutes - php

When the user logs out by closing their browser or by restarting their PC, how do i save the loggout time in the database?

I managed it with a kind of user-ping. Every page in my web-app uses a javascript wich makes a get-request every minute to a certain php-file. This file identifies the user and updates a last-activity timestamp in my user table. On the server I made a cronjob that triggers every 2 minutes and checks the usertable for last-activity timestamps that are older than 2 minutes. If there are timestamps older than 2 minutes you can mark the user as "logged out". This way the user can spend long time on one page and won't get logged out due to inactivity. If he closes the browser or restarts the pc the logout timestamp will be set by the cronjob and is pretty exact.
This solution works well, but uses javascript timers. It is not really nice, but makes it's job pretty fine. If your page allready uses a lot of other javascript you perhaps should use a other solution.

If they are not physically clicking the log-out button (where you are recording their log-out time), you should set the log-out time to the session expiration. In order for this method to be more accurate, decrease the lifetime of the session to a couple of minutes. Thus, after a couple of minutes of inactivity, the session will expire and your log-out time will be relatively close to when the user stopped using your software. See below on how to record this information. Cron job or javascript implementation is necessary.
Just my two cents... probably better ways to do this, but this way seems to me as the easiest.

Related

is it possible to update mysql with timed intervals without a client request

I have working on game where users can send each other challenges. These challenges have timed intervals, say hours, days etc.
When a user logs in the times set can be retrieved through mysql then displayed as a countdown clock using java script to show and countdown remaining time. If the time runs out the database can be updated to display this. This works fine if users are logged in but what if the time set ends when nobody is logged in.
So is there a way of running something constantly on the server to check these countdowns and change the database if the time has ran out or would it work better check the timer when a user views the challenge then act accordingly.
to clarify:
Option 1. Automated script that runs on a server checking the times of each challenge. Either by having a computer constantlylogged in running an ajajar request with an interval timer. (Preferably without a computer and ajax)
Option 2: when a user views the challenge the time is worked out. If the time has ended update this in the database so the challenge now shows up as ended.
If option 1 is possible is it better and how would this Work?
Yes, you can. Use dates. Go with date_created and date_expired. If the current time exceeds the date expired time, etc etc.
are you looking to delete the expired challenges? or set a flag, so the user knows they existed but expired?
depending on your SQL version, look into 'Events'. it's similar to a CRON job, but is run on the SQL server. i would say this is a good option if available to you.

Record time user is on a page safely

How to measure a time spent on a page?
I came across the above thread, which has a solution, but the user could easily modify the inital date value making the time they spent on the page any time they wanted.
I need to somehow get a rough estimate of how long the user was on the page that the user cannot modify.
Any ideas?
First, you need to determine how important seconds or minutes are.
Measure the time spent on page using javascript.
Implement a heart beat with an unique id per loaded page, which runs every n seconds or n minutes to update how long a user has stayed on your page.
Call the same heartbeat function using onbeforeunload too (which fails many times, but when it works it will improve your accuracy).

PHP best practice keep track of logged in users

I want to show users who else is logged in as part of a comment system. What are best practices for keeping track of users? For example:
Do you keep track of all sessions and then mark them as closed. Or do you delete users upon logout, keeping track only of active users.
I'm thinking I should create a table with userid, time logged in, time logged out and/or status. Is that the way to go or is there some alternative approach of tracking session ids. If using a table, is there value in keeping sessionid. Should I delete row when session no longer active, negating need for whenloggedout field.
There is a login so easy to keep track of users logging in. However, it is harder to track users logging out since their session may be broken by browser crashing etc.
Is it best practice to consider users logged in as long as they have not destroyed session... for example, FB and Gmail will leave you logged in almost indefinitely--or should there be a time limit since last activity? The idea of saving to this table every time there is activity on site is not appealing.
Right now, I'm thinking of following:
create table loggedin (userid (int), whenloggedin (datetime), whenlogged out (datetime), loggedin(tinyint))
with the latter going to 0 either if whenloggedout not null or after some long time limit like 24 hours. I imagine FB while leaving you logged in for long periods of time, also keeps track of activity for purposes of chat etc. but not sure. I'm also thinking of letting the table expand, rather than deleting closed sessions but maybe that's a mistake.
Would this approach be considered adequate or is there a better way. Many thx for advice on this.
Depending on how you want it to work you basically have two options:
Define a timeout after which you consider a user logged out
Use ajax/websockets/whatever to poll user
1: Timeout
This is the simpler use case. Every time the user requests a page, you update a timestamp in your database.
To find out how many users are online, you would do a query against this database and do a COUNT of users who have been active in the last N minutes.
This way you will get a relatively accurate idea of how many people are actively using the site at the moment.
2: Constant polling
This is a bit more complex to implement due to having to update the server with Ajax. Otherwise it works in a similar fashion to #1.
Whenever a user is on a page, you can keep a websocket open or do ajax requests every N seconds to the server.
This way you can get a pretty good idea of how many people have pages open on your site currently, but if a user leaves the page open in their browser and doesn't do anything, it would still count them as being online.
A slight modification to the idea would be to use a script on the client to monitor mouse movement. If the user doesn't move the mouse on your page for say 10 minutes, you would stop the polling or disconnect the websocket. This would fix the problem of showing users who are idle as being online.
To circumvent the problem with knowing if a user has logged out or browser crash ect, is to use a heartbeat/polling of sorts here is a stripped down example of how you can do that with jQuery
function heartbeat(){
setTimeout(function(){
$.ajax({ url: "http://example.com/api/heartbeat", cache: false,
success: function(data){
//Next beat
heartbeat();
}, dataType: "json"});
}, 10000);//10secs
}
$(document).ready(function(){
heartbeat();
});
http://example.com/api/heartbeat would keep the session alive & update a timestamp in your db, then on each page load you would check the time stamp with current time ect and if its lower then say 15 seconds then you would log them out.
Constant Polling and using heartbeat are a good idea, but for some scenarios they may create useless load on server. I think you should think about the importance of keeping track of your users and use it very appropriately, especially considering the impacts your changes may have on load time.

Updating db tables based on user activity

I have log table for all users of website
I'm recording various data about user righ after successfull login.
If signout_dt field not filled and status is 1 for some user_id, website prevents login automatically.
For that who have cookies - there is no problem.
The problem is,lets say user signed in without cookies: only sessions variables. I have no idea, how can I update db table and signout user let's say after 30 minute inactivity. Note that I can't create cron job or something serverside, because using shared hosting.
Heard that, it's possible to create some script like heartbeat that continously sends some data about user activity. But I think this will heavily load the server especially if there are more than 1000 users.. Any suggestion, tutorial, article, something else?
Update
Deceze tried to explain but I really need better explanation (better idea), with code.
To "timeout" a user, simply note the time he was last seen. Then, when necessary, check if the last time you've seen the user was over x minutes/hours/days, and consider the last session timed out. You don't need to run a cron job or anything that cleans up after users in realtime, you only need to be able to determine if some information should be considered stale when you need that information.
You may want to occasionally run a cron job or something to clean out old, unnecessary data, but that doesn't need to happen in realtime. You could even run this as part of a regular page request:
if (mt_rand(1, 1000) == 1) {
mysql_query('DELETE FROM `table` WHERE `last_seen` < some point in time');
}
To note the last seen time, just run this query on each page load:
UPDATE `table` SET `last_seen` = NOW() WHERE `user_id` = ...
To avoid thrashing the database with these queries, you can also just do it every so often. Keep a "last_seen_last_updated" timestamp in the user's session, then on each page load check if you might want to update the database:
if ($_SESSION['last_seen_last_updated'] < strtotime('-5 minutes')) {
mysql_query(...);
$_SESSION['last_seen_last_updated'] = time();
}
That gives you 5 minutes of jitter, but that's usually perfectly acceptable.
Your management of sessions is broken and does not conform to accepted stateless behaviour - in as much as you apparently require the user to sign out, which rarely is the case in web applications -- most people just closes the browser, and the cookies will just float around and appear next time the user accesses the website. If the system wants the user to sign in again, then the web server will have to validate the session -- for example using a timestamp and/or cookie signing etc, and invalidate the cookie to force the user to re-login if needed.
Hence you should treat cookies and sessions variables the same -- that is; have your server side generate a unique signed value. Keep an expiration time (for example now()+20min) either in the cookie/session variable or keep the expiration time in the database.
At each access check that the cookie/session-variable is correctly signed, and check that it is not beyond the expiration time, and update the expiration time to allow another 20min.
If the access is past the expiration time -- i.e. the user has been idle for too long, then clear the cookie/session-variable and force the user to login again.
If you keep the expiration time in the database, you simply write a small program which once and day or once an hour run though all records and remove those which you deem too old.
As per my understanding of your question, you want to address following things:
a. If for a given period of time, a user is inactive then he should be logged out and your database table gets updated. Here being inactive means, user has not used keyboard/mouse for a given period of time.
b. If a user closes the browser without logging out, then he should be forcefully logged out and database table gets updated.
Both these things can be accomplished using Javascript Functions and Ajax. Following is the flow which we have in our application for addressing above issues:
Create a Javascript function, say logoutUser(), which will send an Ajax request for updating the database tables and destroying the session.
Use Javascript function - setTimeOut - to call logoutUser() function after time period you have set for inactivity.
Use Javascript events to catch mouse movement and keyboard activity and in every such event call use successively clearTimeOut (in order to remove the old time for execution of logoutUser()) and setTimeOut (for setting the new time of execution of logoutUser()). This way you would be able to catch the inactivity and logout the user after a period of time.
For taking care of the issue related to closing of browser window use 'onbeforeunload' event of javascript and in this event send the Ajax request for updating the database tables.
As our application uses ExtJS, thus, we have used ExtJs library functions to detect events. You can also prefer using some Javascript library for catching the events and implemeting the above solution.
Hope this helps.

PHP, how do I calculate total online time of a user?

What is the best way to calculate the total time spent by a registered user on the site? ...under these conditions
1) User logs out normally.
2) User can simply close browser.
3) User can auto-login next time he comes back.
I think the best way to do this would be to find the time spent by the user on each page and keep adding them to his total time instead of checking for the whole site. But I don't know how to implement that....please help
You can't find the exact time he leaves the system, unless he logs out. Even then, he might be browsing the site while logged out.
The approximate way to do this would be to set the start time in the session and keep incrementing the time everytime he visits a page.
So the first time the user comes to your site at time T, you will
Create a session and put the start time there
Add the total time as 0
For all subsequent requests you would
Check the start time and compare that with the time now and get the difference
Add that time to the total time
This method will not give you the time the user spent on the last page. But it will give you something to work with.
You can do this with JavaScript and a separate PHP script.
The javascript code reacts to events that mean that an user is active (such as mouse/keyboard/resize events) and invokes the php script.
The php script compares the time when it last received a request to the current time and checks if the difference is over a certain threshold (i suggest something like 10-30 minutes to prevent single-click sessions from adding up) nothing happens.
If the threshold is not reached then the difference between the two timestamps is added to the total sum in the database.
Afterwards (in both cases) the last request time is set to the current time and the script ends.
If you also want to know when the user closes your website pages you can subscribe to unload events and/or implement an heartbeat script that calls a PHP script every X seconds.
you have 2 approaches, either to create a log table in your DB to track each user (by ID) logins and logouts and then calculate the time difference between the two in each record for the specific user and then sum all of that. OR you go more complex and make 4 columns in your DB->usertable (logintime 'timestamp' - logouttime 'timestamp' - lastactive 'timestamp' - onlinetime 'int') and update each column as their names say by code according to user activities. then alter the Session.php script in the System/libraries directory at line 105 exactly after if ( ! $this->sess_read()) before the system creates a new session and write a code to check if the 'logouttime' is not the same as 'lastactive' time (to avoid session timeout expiry misunderstood in the next code) if both fields not the same, update your DB to make 'logouttime' equals 'lastactive' then at line 107 exactly after: $this->sess_update(); write a code to check if the 'logouttime' equals the 'lastactive' (and you will make that happen earlier in your logout.php script) write a code to calculate the online time by the difference between the 'logintime' and the now time 'time()' and add the result to the 'onlinetime' field. but if the 'logoutime' is not the same as 'lastactive' (that meanse the user is online and making activities in your site because you are tracking him and updating the 'lastactive' field frequently) then write a code to calculate the online time by the difference between the 'lastactive' and now time 'time()' and add the result to the 'onlinetime' field. that way you have the exactly online time logged forever in the 'onlinetime' field! I hope you got me right because the examples will be a lot long of scripts (although I don't mind to share upon request). good luck.
Use the Session ID to keep track of individual sessions.

Categories