Get dynamic time and timeout after certain amount of time - php

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.

Related

How to get around server flooding by users opening countless tabs?

I have some kind of chat/forum application that checks for new messages using periodic polling (every 15 seconds) using jquery ajax. I was wondering if i can get around the issue of users who try to be 'funny' by loading several same browser instances, with lots of tabs, all pointing to the same application. Each tab is sending an ajax request, which potentially can overflow a server if several users start to do the same thing.
I do store sessions in a table, along with the last access time and IP address, which works fine as long as users don't use the same browser. I could store a unique identifyer that is sent using the ajax POST or GET request, but that would give problems if a regular (non abusing) user refreshes his page, which would then create a new identifyer.
This is not a real problem yet, but better catch it before someone thinks of abusing the system like this :) Any idea how to do this?
One option could be to fetch data like so:
Your script is preparing to poll data. Before executing the request, write (with LocalStorage), a value saying that you're going to fetch data. localStorage.setItem("last-request-timestamp", new Date().getTime());
Poll for data. You get a result. Write that result to the localStorage: localStorage.setItem("latest-messages", ajax_result);
Check if a page is preparing to poll data by checking if localStorage.getItem("last-request-timestamp") is longer than 15 seconds ago. If so, go to step 1. If not, wait 15 seconds and check again.
Regardless if the current page polled for data or not, check the latest-messages variable and update the page.
Other pages will of course share the localStorage data. They won't get data if another page is fetching at the moment. If page #1 is closed, one of the other pages will continue to fetch data.
I haven't used LocalStorage before, but browser support seems decent enough. You should also be able to just use it as a key-value array: localStorage["last-request-timestamp"].
You can only store strings in localStorage, but you can of course serialize it into JSON.
Not sure if it is do-able in javascript. You can check if the tab is active. And only do the ajax on the active tab?
I have the similar problem. Now I force all users to log in (it means i have their e-mails). Also i setup connections limit per account and request limit per connection, after 5 overflows i ask user to enter captcha, then i block account for a 30 min and send e-mail with password recovery link. It's not a clear solution but for now it works for me.
UPD:
The simplest way to do this is to use cookie or session storage. I use cookies. The algorithm is simple:
User login on web.
Check is there any opened session for this user,
is opened, then delete the other session or trigger exception or
switch to that session, you have decide your own the desired
behavior.
Create session id for user and store it in database.
Increase sessions counter field for specific user to detect opened
sessions, so now it doesn't matter is there one browser in use
or many.
Update last access mark (i use microtime(true) + $delay and mysql
decimal(14,4)). Send it to user
Send id to client
On each request:
Search for session by passed id in $_COOKIE.
Check last access mark. If it less then microtime(true) it means that client send requests to frequent, so decide yourself what to do, increase the mark, for example microtime(true) + $delay + $penalty or drop whole session or trigger error. The behavior depends of your application.
Why not throw something like Memcached/Redis at the problem? Cache a response with a 10-15s lifetime and avoid as much processing as possible.

Logging Activities: How to record time using a PHP application?

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.

How to calculate how much time the user is on a web page?

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
}

Counting the time a user has been connected to a site

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.

php with javascript timer - what happen when user leaves the page before the timer is zero

i have a game whene the user can win something.
as soon as he wins he has 60 seconds to fill in his adress name etcotherwise he lose his price and someone else can take it.
when he not fills in the adress in 60 seconds then he gets redirected to a sorry too late page and he lose his price.
when he fills in his adress he gets redirected to a confirmation page and can claim his price.
i made this with php and the counter is in javascript.
the javascript will do the redirect when time = 0
how can i controll that the user either goes to the confirmation page or to the soory to late page.
i'm wondering how i can be sure that the javascript countdown is really counted to zero even wehn the users leaves the page.
thanks a lot
You can't be sure - your users can easily modify your javascript to increase the time limit or even disable the timer completely.
The time limit should be validated on the server. I would suggest that when the time limit starts the server stores a row in the database storing which user it is and when the time limit started. When the user submits the server should check the database to see how much time has passed.
I also think that having just 60 seconds to fill in your address is rather harsh, but that's your decision.
try not to trust only javascript for this job, use php to write the time in the session or an database when the user gets the form to fill in his data - check the difference (with php) between this starting-time and the end-time when the user submits the form to the server
and show him the confirmation when diff<=1min or show him sorry-to-late when diff>1min
you could do this, use javascript for user interfase, and when user leaves a filed execute ajax call to php script and save data that he just entered in field. And real counting make in php, so when user submits final data u should also check if time expired in php.
I think this is good solution for your problem.
If you do this in Javascript, anybody can read your script and find where the prize page is.
Instead, run your timer with PHP using microtime(). You can start when they see the "You Win" page. It will run in the background, and won't depend on any user interaction.

Categories