I have a website, and I have to implement (with PHP and/or JavaScript) an alert message that triggers two minutes after a visitor has entered the site. I've searched, but all solutions I've found are for an unique page. I need the timer counter to start when the user enters my site, no matter through which page. And I need that counter keeps counting while the user navigates my site's pages.
One solution could be using session variables. I can make a script that looks for this variable, if it doesn't exist means that the user is entering the site. Then I set this variable with current time. The script it's in each page, and it will be reading this variable via AJAX each x seconds and I'll know when the user is in my site since two minutes.
I don't know if it's right or not (I've not implemented yet), but I'm not pretty sure if session is the best way. If the user leaves the page but has other navigator windows opened, the session doesn't expire, and if he enters the site again, the counter will not be reset.
So, two questions:
Is there a better method to have
more control on the real entering
and exiting?
If not, is my above
approach right?
Thanks.
Something like this should work.
$alert_message = false;
if(!isset($_SESSION['time_entered'])){
$_SESSION['time_entered'] = time();
}
if($_SESSION['time_entered'] =< time() - 120){
if(!isset($_SESSION['message_sent'])){
$alert_message = true;
$_SESSION['message_sent'] = true;
}
}
And in <head>:
<?php if($alert_message):?>
<script type="text/javascript">alert("You've been here for at least two minutes.");</script>
<?php endif;?>
Also make sure that you have session_start() at the top of every script.
You don't need AJAX, you just need to store the time in a session variable, and then include some JavaScript on each page, here is an example:
<?php
session_start();
$time = microtime(true);
if (!$_SESSION['foo']) {
$_SESSION['foo'] = (microtime(true)+120);
}
?>
<script type="text/javascript">
var timeoutID = setTimeout(function() {
alert('two minutes have passed');
}, <?php echo bcsub($_SESSION['foo'], $time)*1000 ?>);
</script>
You will need some additional logic so that it does not keep firing after the 120 seconds are up.
Related
I want to find how much time has passed from the beginning to the end of the visit on page. I have a theory which is that, function get the time which comes by end of load, then when user leaved function also get leaving time and it calculates this times yet I do not know how to do this.
Get time using javascript when page loads and store the variable in session, and detect the page close event in js and store it in another variable so that you have the page load and unload time in two variables.
PHP is a server-side language, so your code only runs on the server. You can however use JavaScript to repeatedly run some code that invokes a PHP script that updates a last_seen value in a session variable for the page.
For example you could try something like this...
Example PHP snippet in home_page.php (PHP part)
<?php
$pn = "home_page";
session_start(); //needed for $_SESSION
$_SESSION["visit"][pn]=["first_seen"=>time(),"last_seen"=>time()];
?>
Example JavaScript snippet in home_page.php (JavaScript part, assuming JQuery)
<script>
var pn = "home_page";
setInterval(function(){ // every 1 second
$.get( "time_keeper.php?page="+pn); //don't care about success
}, 1000); // precision of 1 second
</script>
Example time_keeper.php PHP script
<?php
session_start(); //needed for $_SESSION
$_SESSION["visit"][$_GET["page"] ?? "404"]["last_seen"]=time()];
?>
Example of a see_time.php PHP script that outputs the time spent on a specific page
<?php // usage: `see_time.php?page=home_page
session_start(); //needed for $_SESSION
$t=$_SESSION["visit"][$_GET["page"] ?? "404"]];
$z=$t["last_seen"]-$t["first_seen"];
echo "You've been there for $z seconds.";
?>
home_page is the name of your page: change it to be uniqe for every additional page, as needed.
I have a strange problem in my online test management system.
Some users in the test form (test.php) need long time to answer the question and submit the form.
After submitting the form the session is expired and user must login again
this is not a code problem
I set this value in top of all pages
ini_set('session.gc_maxlifetime', 18000);
Is there a way to refresh the session evrey 10 minutes without reloading the page in test form to prevent session expire?
Please help me
Thanks
You can use javascript XHR, or as others call it, AJAX.
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.get/
Using ajax you can call a php script that refreshes your session every 10 minutes. :)
This is as far as i can go to "exact".
javascript
var refreshSn = function ()
{
var time = 600000; // 10 mins
setTimeout(
function ()
{
$.ajax({
url: 'refresh_session.php',
cache: false,
complete: function () {refreshSn();}
});
},
time
);
};
// Call in page
refreshSn()
refresh_session.php
<?php
session_start();
// store session data
if (isset($_SESSION['id']))
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
?>
Anyway, another solution would be to extend the session time for the test page only using
the solution presented here
How do I expire a PHP session after 30 minutes?
All you need is this (uses jQuery for the $.post):
JavaScript (put this inside your onload-function or something)
setInterval(function(){
$.post('path/to/refresh_session.php');
},600000); //refreshes the session every 10 minutes
refresh_session.php
<?php
session_start();
// if you have more session-vars that are needed for login, also check
// if they are set and refresh them as well
if (isset($_SESSION['token'])) {
$_SESSION['token'] = $_SESSION['token'];
}
?>
The biggest change is in the JavaScript--you don't need a whole function, just one line.
EXTRA INFO
Although I think it's enough to just call session_start() in the php, if I read this right (http://nl3.php.net/function.session-start):
The read callback will retrieve any existing session data (stored in a
special serialized format) and will be unserialized and used to
automatically populate the $_SESSION superglobal when the read
callback returns the saved session data back to PHP session handling.
And during testing I only put the above code on my visitor page, and not on the admin page. But I had both pages open in the same browser (Chrome), and the admin page stayed logged in as well, at least for over an hour (didn't check any longer).
BUT, I don't know if it still works if you only use session_start(), without manually refreshing any session-var at all..
Either way, I like to be sure that the session-vars I need are really still there:)
Javascript:
function doStayAlive() {
var request = new XMLHttpRequest();
request.open('GET', 'stayalive.php', true);
request.send();
}
timerStayAlive = setInterval(doStayAlive, 600000); // 10 minutes
PHP: (stayalive.php)
<?php
session_start();
http_response_code(204);
?>
There is no need to "touch" session variables
I have a system where the user logs in and is immediately directed to a PHP page that runs some queries which it inputs into session variables. After the PHP has finished executing, it redirects the user to the main page. I would like to know how I can set it up, so that when the user refreshes the main page, it redirects them to the preceding page where the calculations can run again before the main page is displayed. I simply cannot have the two pages merged together. Does anyone know how I can accomplish this?
EDIT: PHP include is the closest to what I need, but the problem is that when I use AJAX to submit a form, the session variables in the first file update with new data from the database. Those variables need to stay static until an actual page refresh by the user. Does anyone know how I can include the form but make it invisible to Jquery?
You could store a value to the $_SESSION and every other load, forward to the other page.
// Start session
session_start();
// If the session variable is set...
if (isset($_SESSION['loadCount']) {
// Increase the count
$_SESSION['loadCount']++;
// If it is even...
if ($_SESSION['loadCount'] % 2) {
// Reidrect
header('Location: /calculate-again.php');
die();
}
} else {
$_SESSION['loadCount'] = 1;
}
In the login form, make it submit to page_with_awesome_calculations_and_queries_to_session_variables.php. Assuming no input is sent in that page, make your calculations queries and sessions there, and then send a Location header to the new page.
header('Location: 'index.php');
This will cause the address bar in the browser to actually change to index.php, and a refresh will make the user stick there.
You should also secure your page_with_awesome_calculations_and_queries_to_session_variables.php to not allow access unless the correct $_POST variables are set.
Have mainpage.php receive one url parameter t which is the epoch timestamp.
Whenever calculation.php redirects to mainpage.php it will pass the epoch timestamp. If mainpage.php finds the epoch timestamp is older than five seconds, it will redirect back to calculation.php and exit.
mainpage.php
if (time() - $_GET['t'] > 5)
{
header('Location: calculation.php');
die();
}
else
{
// proceed normally
}
calculation.php
// perform calculation
header('Location: calculation.php?t=' . time());
Add
<?
require 'calculations.php';
// Mainpage goes here
?>
to the top of the mainPage. This makes it an extension of the mainPage which is run before the main page is loaded.
What would the best way be to logout a user from a PHP application (so basically just perform a redirect) after X seconds of inactivity? For "inactivity" I'd count the time of the last page load, and if the current time is more than X seconds away, perform the redirect.
Is this something that would need to be achieved with Javascript?
You can use just html meta tag:
<meta http-equiv="refresh" content="1000;url=buy.aspx">
put it in head
where 1000 is a time in sec and url is an url to redirect.
Just answered this question yesterday... the OP wanted to ask after certain amount of time, it the user would like to stay logged in or not.
For a plain redirect without any confirmation, you can use a simple setTimeout call:
var minutes = 30;
setTimeout(function(){location.href = 'logout.php';}, minutes*60*1000);
Do you really want a redirect for some reason?
Usually each user session has an associated timestamp. You then make sure the session hasn't expired for the user, or ask them to log in. So in effect, you're just making sure sessions are valid.
If you redirect someone to a logout page, you really are not achieving anything. You will also need to make sure the session has not timed out server side. Anything that is client side, including redirects to a logout page, is unreliable, and can be circumvented.
The simplest form in PHP:
<?php
session_start();
$session_lifetime = 60*60; // 1 hour
if (!isset($_SESSION['time']) || !$_SESSION['time']) {
$_SESSION['time'] = time();
}
if (time() - $_SESSION['time'] > $session_lifetime) {
// session has expired
$_SESSION['user'] = null;
$_SESSION['time'] = null;
} else {
// keep session alive
$_SESSION['time'] = time();
}
What if the user starts typing in the form on the page and hasn't finished by your time out period? I handle inactivity in another way than described in other answers so far.
var rowLockSeconds = 0;
function startRowLockTimer()
{
setInterval("incrementRowLockTimer()",60000);
$("input").keypress(function (e) { rowLockSeconds=0; }).click( function() { rowLockSeconds=0; });
$("textarea").keypress(function (e) { rowLockSeconds=0; }).click( function() { rowLockSeconds=0; ; });
window.onbeforeunload = function obul() { if (hasChanged) { return 'You will lose any unsaved changes you\'ve made.'; } }
window.onunload = clearRowLock;
}
So as they've logged in, the row lock timer starts at 0. Every 60 seconds it calls the interval function to see if it has timed out.
function incrementRowLockTimer()
{
rowLockSeconds = rowLockSeconds+60;
// 10 minute timer to clear someone out of a page if there has been no activity
if (rowLockSeconds >= 600)
{
window.onbeforeunload=null;
// clear rowLock with request here
$.get('../ajax/rowLock-server.php?do=delete&rowLockID='+currentRowLockID+'&userUUID='+currentUserUUID, function() {
alert('You have been logged out of this page after 10 minutes of inactivity.');
document.location.href='../main.php';
});
}
}
The AJAX controls clear out the DB row lock.
The key is the input and textarea bindings so that if the user types anything into the form, the timeout is reset and they have another 10 minutes.
I want to have a timer going to run every 3 minutes on the page (javascript), to detect if a php session ($_SESSION) has timed out... and if so, redirect them automatically.
A good example would be, a user logs in and runs up stairs, and never comes back down... I want the javascript to log them out with a simple redirect...
Is this possible? and how would I do such a thing? I am using PHP and JavaScript.
What Rob Kennedy said below is exactly what I am looking for:
...when the session times out,
the browser should be told to navigate away from the current page.
Some banks do this after a period of inactivity, for example.
You could use a simple meta refresh:
<meta http-equiv="refresh" content="180;url=http://example.com/logout" />
Or you implement a timeout with PHP:
session_start();
if (isset($_SESSION['LAST_REQUEST_TIME'])) {
if (time() - $_SESSION['LAST_REQUEST_TIME'] > 180) {
// session timed out, last request is longer than 3 minutes ago
$_SESSION = array();
session_destroy();
}
}
$_SESSION['LAST_REQUEST_TIME'] = time();
Then you don’t need to check every 3 minutes if the session is still valid.
New and improved solution
As mr kennedy pointed out my original solution (below) doesn't work. so here is a way to do it.
In the user database keep a last-activity timestamp that updates every time a user loads a page.
Then in a checkaccess.php
if ( time-last_access > max_inactivity_time ) {
return array('access' => '0');
}
else {
return array('access' => '0');
}
Call checkaccess.php in the javascript timer(below) and logout accordingly
This also allows for a "currently logged in users" function
thanks mr kennedy
Original, non-working solution
Create a php page that returns 1 or 0 based on the validity of the current users session
Then in your pages that you want to timeout add this to the head (you need jquery)
setInterval(function(){
var url = UrL_OF_SESSION_CHECKING_PAGE;
$.getJSON( url,
function( data ) {
if (data.access=='0') {
window.location = LOGIN_PAGE;
}
}
);
}, 180000);
Every 180 seconds (3 minutes) it requests the php page and gets the validity of the session. If its invalid it redirects to a login page
If the user has multiple pages open the pages will timeout and redirect at different times because their timers are different.
Here's a good page on javscript timers
http://ejohn.org/blog/how-javascript-timers-work/
Simple session checking page
session_start();
die(
json_encode(
isset( $_SESSION['VARIABLE'] ) ? array( 'access' => '1') : array( 'access' => '0' )
)
);
change VARIABLE to one of your session variables
If you want this to happen before the page is even refreshed, you'll want periodic ajax calls. You can use jQuery Heartbeat to make calls every 3 minutes, and use one of the PHP methods already provided by other users to check the session