session timeout on page with ajax auto-refresh - php

Good day folks - be gentle - I'm a first time poster.
I have a page on a php-based web site that uses an AJAX-based call to update a DIV tag with a table of data every 5 or 10 seconds. The security folks where I work want me to make sure users get logged out after 15 minutes of inactivity.
To that end I put in
<script type="text/javascript">
window.setTimeout("location=('/mysite/session_timeout.php');",900000);
</script>
The problem is, of course, that the AJAX refresh of the table is 'resetting' the timeout counter ...
So my question is basically "Is there a client-side way to either mitigate the ajax call resetting the clock so to speak, or do I need to address this with php's _SESSION array and hide values in there, or does someone have something better than that?"
Thanks for any help you all can provide.

You can Store the start time of that page and update you table data without reloading the page. and check for the start time and destroy session accordingly.

You can try something like this
$_SESSION['activity'] = time();
function check_if_logged_in() {
if(time() - $_SESSION['activity'] > 900) {
// Do redirect or take other action here
}
}
Or you can use this jQuery plugin.

Related

PHP SESSION destroy when user close the browser or automatic session destroy

I have a hole in my login-logout script and i really have no idea how to fill it.
The whole problem appeared when users started to simply leave the page instead of logging out. There actually wouldn't be anything bad about it, because in my code there is logout after 15 minutes(session time out), but in my database there is a column "online" which is changed on login and logout, so when user just close the page it doesn't change to offline.
I was trying window.onbeforeunload to href to page where the logout is (didn't work)
I have heared also about cron but i have completly no idea how to do this.
Can anyone tell me how to solve my problem with detailed explanation?
Looking forward to hearing from you.
A solution could be that each time the page loads or perhaps an ajax request for each page to bounce a code to the server to say "hey, this user is online", and then have a built in function to your scripts (that work on any page, anyone views) to check if the mysql update time is within the last X minutes and if not the user is assumed to have logged out.
I think I've explained that quite badly.
You have a timestamp field in your Table - associated with each user logged in, and they're deemed to be online if the timestamp last update is within X minutes of NOW,
So, each time a page is loaded or each time an ajax call is processed, the timstamp field is updated, and then on any field that has timestamp older than X minutes, this is because they've (probably) logged out and so they are changed in the DB to being "offline". Although if they're just busy and still online, perhaps don't actually log them out, just mark them as offline.
I'm running without details on how you process your database content details etc., so my idea might be well out from what you can create - ?
EDIT:
Ajax Suggestion
For ajax to act on each page every X seconds, write the following ajax onto the page the member is on, be aware that the number at the end is milliseconds, 600000 = 10 minutes. So used 500000 as it's within the timescope. so the ajax function runs every 8.5 minutes, or on page load.
THe ajax is quite poorly written and probably can be improved. But should work. You'll need to research a more optimal ajax script.
BROWSER PAGE:
<script src="js/jquery-1.11.1.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$( document ).ready(function() {
var memberId = <?php print $memberId; ?>;
var securityKey = <?php print some security key code or suchlike to validate this ajax at the otherend;?>;
setInterval(function(){
$.post("/ajaxSession.php",{
MemberId: memberId,
somesecuritykey: securityKey
});
}, 500000);
});
</script>
AJAX PAGE:
Please note update time in this case is a 'timestamp' MySQL field.
<?php
/**
Setup this page as if any other PHP page but this page will never show to the browser,
AJAX data is supplied as $_POST and inn this case $_POST['somesecuritykey'] and $_POST['MemberId']
**/
session_start();
/**
include classes and files
**/
if (is_numeric($_POST['MemberId'])){
$memid= (int)$_POST['MemberId'];
/**Also include your security stuff here **/
$sql = "UPDATE Members SET UpdateTime = NOW() , LoggedIn = 'YES' WHERE MemberId = ? LIMIT 1"
$mysqli = new mysqli();
$mysqli->prepare($sql);
$mysqli->bind_param("i",$memid);
$mysqli->execute();
}
And that should keep the timestamp values upto date, so logged in people is anyone whose UpdateTime is MORE than time()-601 (10:01 minutes), SQL listings can change this on any header/class which occurs when anyone access any page
SQL = "UPDATE Members SET LoggedIn = 'NO' WHERE UpdateTime < (NOW() - INTERVAL 10 MINUTE)"

The best way to have a user log in in expire?

I am exploring a potential in-house content delivery system where we have to keep track of student time-on-task. As long as the student is interacting with the page, there is no problem. If the student goes out for lunch leaving the page open, the session should time-out and they will not get credit for their on-line time after the timeout.
I already figure I can easily capture events like navigating away from a page and recording that fact with PHP into the student's record in MySQL, but what is the best way to time a student out? JavaScript? I looked around and haven't found a good explanation yet.
Thanks for any help!
---------- EDIT --------------
After Floris' suggestion about looking at a particular post about idleness, most suggested a JQuery solution, but one poster had a simple solution with no JQuery. Does this code seem like it will work? It looks fine to me:
var inactivityTime = function () {
var t;
window.onload = resetTimer;
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
};
Use JavaScript to detect when a user becomes idle. When a user become idle fire an AJAX call that blows away any cookies or session data.
A student can easily fake it, if you let the browser do the work. Instead I'd turn it around and log whenever a user does an action (like go to a different page). The time spend is the sum of the time between an action and the next (delta time), but exclude if delta time is bigger than 15 minutes.

Countdown variable across many pages

I have a demo website for an e-test where each student is allowed 15 minutes for the whole exam (which comprises 5 subjects, each with 10 questions). I want it that, immediately a student clicks START on the home page, a countdown timer should start and update itself automatically. Actually, that is easily done for a single page.
The problem is if the student clicks to go the next page, I want the timer to begin from where it stopped on the previous page and continue counting down.
I thought of using SESSIONS but then how do I get Javascript to set the SESSION variable in PHP? The idea was to use AJAX but I do not know how to go about it.
Can anyone help me on it, even if it requires something other than AJAX?
PS:
What I want displayed is the number of seconds left, not the current time.
Thanks.
You don't have to know where it stopped on the other page.
You just want to know when the users clicked start.
Just save that in a database or a file even.
And on every request calculate the time left on the SERVER.
Since the client can be easily manipulated.
With the time left calculated on the server you can make a countdown using javascript on every page.
I found i simple way to do it, with a small search. Here
PHP:
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You can use an algorithm like this:
When the "start" event occurs, store the start time in a database.
Periodically send AJAX requests to a backend script. If the time has expired, return a response that ends the test.
There is not a real "timer" in this case -- just a start time, and logic to check if 15 minutes have passed since that time. If you want to display a timer to the user, the math will be straightforward.
You could just put the pages in IFrames and the countdown timer on the main page.
Simple, you store the timestamp of when the student first started the test and output it to each page. Then it's a simple matter of substracting current time from that timestamp to get elapsed time.
However, depending on Javascript is a very bad way of ensuring that this timer gets started. A better method is to force the user to click on an actual link/button, WITHOUT involving Javascript. You record the timestamp on the server then that hit comes in, and after that everything's fine.
start.php:
Start Test - Page 1
page1.php:
<?php
if(!isset($_SESSION['test_start_timestamp')) {
$_SESSION['test_start_timestamp'] = time();
}
?>
<h3>Question #1</h3>
etc...
The important thing is to never reset the timestamp value in the session once it's been set. Otherwise the test taker can simply click around until they reach a page where the counter's reset, and they can get more time for the test.

Is this the best way to update user status?

Status as in online/offline..
When a user enters onto a page, it records the current time and puts it in the database.. if 5 minutes passes since their last action, it shows them as offline?
You can use JavaScript to time the five minutes, then use AJAX to call a PHP script that updates the database.
window.onLoad = function(){
setTimeout(UpdateDB,1000*60*5);
}
function UpdateDB(){
// AJAX call...
}
This would be a good way to start. You can easily check the period of inactivity.
It would be relatively simple for you to set up an AJAX ping to your server on a long interval~ so that as long as the user's browser has your site loaded, it's still pinging it's status as online.

After 30 seconds, update MYSQL database

I've been looking around here on SO and Googling, however I can't find anything that fits my description.
What I want to do is update the database if the page has not been refreshed after 30 seconds. I want to email a person with the contents of a form {submitted by a different user} (I can do that) IF the person has NOT visited the page (I can do that) within the last 30 seconds.
What I've tried to do is make the page that should be visited refresh every 30 seconds, and so I figured if I did something like after 31 seconds, edit the database (so if the refreshed page was not refreshed, the database editing would run).
I'm sorry if this sounds complicated, there's probably a better way to do this, but I'm not sure how.
The bigger picture is I'm trying to make a 'on-duty' sort of thing, so that if the person is not actively looking at the page, they will get emailed with whatever the contents of the form is. The page will contain a table of all the entered form results.
You could update the database by creating a record with a timestamp every time the user refreshes the page. Then, you can have a PHP worker that looks regularely in the database if the timestamp is older than 30 seconds, and starts the e-mail.
I can't provide php solution for the server-side part of the job. But basically you need to set up javascript timer (eg. jquery timeout) and after 30seconds do the ajax call that will do what you want on the server (save something to db, send email and so on).
I hope I got your point and my advice will help you somehow.
maybe use an AJAX call every 30 secs based on the setTimeout javascript function?
http://www.w3schools.com/js/js_timing.asp
function timedCount()
{
# ajax call
t=setTimeout("timedCount()",30000);
}
I would suggest using javascript like this:
window.setTimeout("location.reload(true);", 3000);
This is of course if you desperately need to reload, but the user will obviously be mad that you reload the window for him.

Categories