At the moment I'm using this SQL to check if a user is connected:
date_add(last_activity, INTERVAL 3 MINUTE) > NOW()
This is passive and will only trigger when a page is loaded.
What I'd like to do is a system that checks if a user has remained connected during a given span of time and give them bonus points.
What do you suggest to achieve this? Use polling or another approach?
You need to use some kind of java script that will report activity using ajax to your site in intervals of like 1 min. You need to implement some sort of mechanism to check if user is active, like if the mouse moves or page is scrolled, because some users can use the same page for long times. If the page is not used since the last min(should be a global var in javascript, set to true every mouse move, and to false every time a message is sent) you don't send a message.
When you receive the ajax notifications in the server you check the time between the last ajax notification(should be stored in database) and current notification and if its smaller than an interval (maybe 2 mins) give the user points for it.
As said you can use AJAX and alternatively the Refresh META tag. Note that if I see a browser tab constantly refreshing, I close it as it is distracting. Of course, if you're offering a service that requires frequent refreshes (chat / shoutbox, ticker) then it's less disturbing.
I currently have 14 tabs open, some of which for days which I haven't really looked at, so you gotta ask how valuable your information is. As far as I know, javascript is unable to get the current mouse position if it's not moving over something that has the mousemove event handled, so implementing "is the page in view and the user moving her mouse" may prove to fire a lot of events when user is active.
I may be oversimplifying here, and this probably won't help much if you're trying to charge for time on the site or something like that, but this is something google analytics takes care of. Time on site is a metric they actively record.
Ok. So here is my idea. As I mentioned in comment my way would be javascript timeout and AJAX.
So the idea would be something like this:
Make a global variable for mouse position.
Set timeout for function to fire in around 10 second intervals (which can grow in time).
Function compares last mouse position with current mouse position. If it has changed user is presumably active.
Update global variable for mouse position. And send data to server-side.
Rinse and repeat...
Actually thing that changed can be anything if you want, but mouse position would be most suiting I think.
Related
I'll try to explain my question the best way I can.
I'm not asking for codes, only for the best method of doing it.
I want to create a browser game and use time for upgrading stuff, building etc.
For example, to build 1 house will take 1 hour.
So I will began with saving the timestamp+(60*60) at the moment the user did his action.
My question is, how to update it the best way?
One way I thought of was to add function that check every page view of the user if it's done.
But then if he's not logged in the update wont happen.
Second way i thought about is for every page view of any user to check for every user registered. But it's not effective and there is a problem if no user is logged in.
Any suggestions?
I had my game doing it simply, without crons.
When a player wanted something that takes time, i just updated his database information with the appropriate time of ending that job (columns are just examples)
UPDATE player SET jobend = UNIX_TIMESTAMP() + (60*60*4) # ending in 4 hours
Then, every page that had an information about the remaining time, i just used something like this:
SELECT (jobend - UNIX_TIMESTAMP()) AS jobremaining FROM player
I formatted correctly the time using strftime and i displayed that to the user.
In the case the remaining time was negative, the job was done.
There was no-need for absolute counting since user was able to do something with the job when he was connected.
When the player just changed pages or doing something else i had a function where i just checked all timely events while the user was online (so to catch any negative timer), then presented with javascript any change (i posted javascript counters for every page)
Now, if you talk about updating in real-time, cron is the way but are you sure you're going to need it for a game? I asked that question myself too and the answer was not.
EDIT
If another player sees the buildings on schedule page (an hypothetical page) i am doing the same calculations; if a time just got negative for a specific player (regardless if another player see the page), i just reward him with the building (in database i make all the changes), even if he's offline. There's no harm in this, since he can't do anything anyway. The other players will just see he has a building. The key here is that i execute the required updating PHP code regardless of player's connection to the game; as long at least ONE player is logged-in i'm executing the progress function for everything.
This isn't so slow as it sounds (updating all players by using just a connected player that visits a specific page). You just have a table of 'jobs' and check timers against the current time. More like a single query of getting the negative ones.
I am implementing an online exam portal, so that a user can start the mockup test(exam) and choose the anwsers for each question and proceed to the next question.
Rules for the exam is to give 100question to complete in 75mins.
So I need my back-end code to check each bit of time and track if the current_time not exceed 75min from the Exam_Start_time
How is this possible.
I made it like this for time being
$Start_time
$Current_time
and then check the difference on each page refresh and redirect if 75min limit exceed
But I think its not the better way and if we can trace it dynamically and redirect when the 75min mark reaches to the process the exam result it would be great.
Can any one help me in this context,
Is there a way if its not possible with PHP, HTML to use Javascript to achieve this
Hope to hear from you stacker.....thanks in advances
Store in your database time and some unique id for each user. While user take a test send ajax request with some interval (i.e per minute) to the server with user unique id and check is everything ok with time if not redirect him to another page or block old one with javascript. But think about security, some user can guess and send another's id :)
If user disable javascript there is another scenario. Server closes tests which hasn't been updated for some interval. And also about local time and javascript you haven't to send user's time to server because you have start time in database.
#trejder and #Wiz if think as you do it's better to do not use javascript at all as it can be turned off and request variables can be falsified by user.
I'm working with some existing PHP/MySQL code. I'm logging/tracking certain activities into a MySQL database. Certain access points are being logged. The number of times a user logs-into the system is counted. But, I need to also log the amount of time a user is logged-in, as well as the time the user is in a certain section of the Web site.
Since PHP is a stateless environment, for the most part, what's the best way to record the end-point(s); or when the user logs-out?
Note: I can't force the user to log out, as the browser can just be closed. Maybe I could just put up an AJAX timer that would count the minutes? If so, should I treat activities and time logged-in as different tables of information (MySQL)?
Edit: I forgot to mention we do have jQuery available.
Like you said, you can't force the user to logout, and you can't know for sure whether he's looking at your page or playing Pinball.
A solution would be an AJAX request every, say 5 minutes, to tell your application that the user is active. Unfortunately, if your user has locked his screen and went to play Pinball, you still don't know exactly what he is doing. Also, doing AJAX requests at intervals like this will increase server load, especially in a multi-user environment.
The best solution I think is to simply store the start_time of the user (when he logs in), then to update the end_time at every action he does, and with a session timeout.
Per example:
I log in at 5:00. Update the start_time to 5:00.
I browse to foo.php at 5:01. Update the end_time to 5:01.
I browse to bar.php at 5:03. Update the end_time to 5:03.
I go for a coffee at 5:05.
I come back at 5:15 and my session expired, I need to relogin.
So, you know I spent roughly 3 minutes on your application, since the last action I did was at 5:03 (5:03 - 5:00 = 3). Of course, you can't know exactly if it was 3 or 5 minutes. But you can assume, most of the times anyway, that if I don't do anything on your application (i.e.: execute a script, call, etc.), that I'm not using it.
Obviously, if you can capture JavaScript events like window close it's even better, or if I sign out manually: you update the end_time accordingly.
You need to capture two events.
The onCLose() event for the page and hook that into an ajax call back to your logging system.
The onClick() event for your logout button and hook it into the save ajax handler.
The onClose event will allow you to capture when either the tab/broswer is closed and the onCLick event is obvious.
Now this will not capture times when the browser dies, the machine loses power etc. so there will be instances where you will have gaps and those can be corrected by your login event handler and simply tag the last login event as logout out on the next login. This will however lead to outliers in your tracking of time spent logged in and you will need to statistically deal with those in your reporting.
You can use an extra PHP script that records the last activity and call it via ajax.
You can use javascript to monitor if the user is still active (moved mouse or pressed a key in the last 5 minutes etc.)
EDIT: Almost forgot the important part: your java script must make an ajax request eery X seconds.
So if there was no request in x+tollerance seconds you can consider the session as dead.
im making some statistic codes for my website (im a php developper). I want to calculate how many seconds/minutes the web user stay on any page (like google analytics do) but i have no idea of how to make this. Thanks for any help or scripts!
How are you gathering the data? The common options would be instrumenting the page using javascript, looking at webserver log files, in the server-side request handler or sniffing the TCP/IP traffic.
Doing it "like Google Analytics" implies the former. In which case the way to do it would be to grab a timestamp as soon as possible when the page loads (rather than waiting for page ready / onload event) and compare that value with the previous tiestamp (so you'd probably store that in a cookie). Then you need some way to send this back serverside, and a way of recording and reporting on the data.
Note that trying to fire an ajax call as the user leaves the page, e.g. via onunload, will not work reliably (the page launching the request is at the end of its lifecycle). The important thing here is the ASYNCHRONOUS part. And making a synchronous call will just have the effect of slowing down the website.
You might want to have a look at Yahoo Boomerang - although it doesn't support dwell time measurements out of the box, it's easy to extend. For a backend, you could do a lot worse than Graphite
You can fire an unload event in javascript when the user leaves the page, which sends an Ajax request to your server. Since this may not work in all browsers, especially if the network latency is high, also have a ping script (also with Ajax) which calls your statistics system once in a while as long as the user stays on the page (for example, every 10-60 seconds depending on the resolution you want).
If you want to do it in serverside i.e in php then probably you would need a table allocated for this. say "analytic"
First you need to add this script in every pages. that inserts these data into the table analytic which is $_SERVER['http_referer'] , current timestamp, remote address and current page URL.
Now the calculation part.
basically when a user first lands in your page $_SERVER['http_referer'] wouldnt be from your domain. Then keep the timestamp as the start time.
Now check the next time stamp. If the http_referer is same as previous records page URL then find the difference in the time stamp to know how much the user has stayed in a page.
More or less what am trying to say is find the time between each request from the user.
Disadvantage of this method: When user lands in a page closes it. its impossible to find the time on your site.
A quick and easy method I came up with is pretty useful.
On every page of a site where I want to track time on page, I include a tracker script.
I grab as much info as I can, and make a database entry, including the referrer, the requested/loaded page, user-agent, ip, timestamp, etc.
These timestamps, in conjunction with the user's ip, can be used to determine the time the user was on the previous page (including load time of current page).
The only drawback is that I can't determine time on the last page they visit (which isn't always a bad thing, I can reduce tracking idle time).
Bounces are identified by single entries by a given ip within a specified time period (an hour would probably be sufficient).
At page load create a date object, then when the page unloads create another and substract them. After that you can do an AJAX request to your tracking server, sending the elapsed time.
var startTime = new Date();
var endTime;
window.onunload = function()
{
endTime = new Date();
var elapsedSeconds = endTime.getTime() - startTime.getTime();
//Do the ajax request, sending elapsedSeconds
}
I want to trace each user time spent in my Facebook application.
I really don't have any idea how to code this, help me out. If someone has any ideas or hints, that will be enough.
I am using Graph API.
Either: Google Analytics
The easiest solution of course is using Google Analytics - FBML (Facebook Markup Language)
has a tag specifically for that: http://developers.facebook.com/docs/reference/fbml/google-analytics
That of course doesn't give you data on what a specific user did, but it is pretty good at telling you the time spent on various pages in your Facebook app. And morally its much nicer not to store what a specific user did exactly on your site.
Or: Self-coded solution
If you do want to track everything specifically, you'll first need to store when a page was accessed using PHP when loading the site and then storing in 10-seconds-intervals (or so) that the user is still present, using an AJAX call. To do that, I'd give the page view an ID and send a request to a page like this *i_am_still_here.php?p={page_view_id}* which takes the current timestamp and updates a database entry for that page view.
This solution has one problem: When a user opens a tab in the background and doesn't look at it for 30 minutes, you don't really want to store that 30 minutes as "the user being on the site".
Also, make sure that with whatever self-coded solution you choose, you have to take into consideration that people might have your Facebook app opened in more than one tab.
Your problem is not Facebook related per se. There are many ways you could implement this, it also depends on your particular application.
You could track every click a user makes (timestamp of the click) and then calculate the time spent from that (last click in session - first click in session). This approach is not very accurate off course since you don't know how many time a user was still using your application after the last click.
One other solution that comes to mind right now, would be to fire a XHR (AJAX) request every X seconds that would also log the timestamp in some storage (db, redis, memcache, ...) and you could then do the same calculation from that. It would be more accurate (depending on your interval X).
You can easily calculate the time spent on Facebook by downloading a software called TimRabbit which is a desktop application and starts automatically calculates your time spent on facebook. It only calculates your live time spent and ignores when you are acting as a idle user.
For details visit: http://etechdiary.com/calculate-time-spent-on-facebook/