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
Related
The below code expires a page only on manual page refresh. I want the page to automatically expire the session and log out the user and redirect to the login page.
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || (time() - $_SESSION['login_time']) > 60) /*session expires after 1 minute*/
{
//logout code such as session unset, destroy;
header("Location:login.php");
}
else
{
//page contents if any
}
?>
gc_maxlifetime has it's own issues. So I don't want to implement it. Found another using ajax with php, but want to make sure is there any other possible. please confirm a way to implement this.
Normally, PHP only executes in response to HTTP requests, and therefore sessions are not cleaned until a request arrives. When and how this is done is configured using the session configuration parameters.
While you cannot directly run the session management code, you can cause it to run by configuring the parameters and then simulating a request via cron or a similar tool. Ping your server every minute (or whatever) with an unpublished URL request that sets session.gc_probability to 100 and then starts a session. This will cause the session management code to garbage collect the sessions--which will effectively cleanup any timed out sessions.
You can determine the time of the session with session_cache_expire(minutes);
<?php
session_cache_expire(30);
session_start();
More info: http://php.net/manual/en/function.session-cache-expire.php
You can do like this with jQuery.ajax or another ajax you like:
<?php
$sessiontime = 60; // 1 minute
$time = $_SESSION['login_time']-time()+$sessiontime;
?>
<script>
setTimeout(function() {
$.ajax({
url: '/path/to/logout-file.php',
dataType: 'json',
complete: function(){
window.location.href = 'login.php';
}
});
}, (<?=$time?>*1000));
</script>
you can use meta refresh
eg 30 minutes
META HTTP-EQUIV="refresh" content="1800;URL=../logout.php"
I want to clear the php session array every time a user leaves my page, but my page has links with query strings. I don't want to clear the session array, when a user clicks on a link with a query string. I have tried the following javascript code but it does not work when the user leaves the page.
somepage.php
var url = new RegExp(/somepage.php\?sort=.*/);
if (url.test(document.location.href)){
//do nothing
}
else {
$(window).unload(function(){
$.ajax({
url: 'clear_session.php'
});
});
}
Calling a webserivce onunload is very unrealiable. Why not just unset the PHPSESSID cookie? This wont clean up the session on the server, but it will give the user a new empty session when he visits again.
I am trying to call a php script which destroys session and reload a page after it.
$(document).bind("active.idleTimer", function(){
$.post("data.php?data=active");
location.reload();
});
data.php
if($_GET['data'] == 'active') {
session_destroy();
}
It does not destroy the session, only if I manually open the url data.php?data=active it does, why is that? Thanks!
The problem is that the script you send the request to is using its own session. So, the user has a session, which is different from the session you send the "refresh idle state" request.
One solution would be to just start a timer using javascript and when that timer runs out, just refresh the page.
That's why it only works when you actually access the data.php page.
If you want to use the data stored in the $_SESSION array, you need to start or resume the existing session using session_start(). In your data.php, try this:
if($_GET['data'] == 'active') {
session_start();
session_destroy();
}
Please, take in consideration that session_start() should be used before you send any output to the client.
Hope it helps!
Modified:
$.post("data.php", {data: active}, function(whatever){}
and in your php file use:
$_POST['data'];
I have users login/logout application:
I want to destroy session, its working fine when I close the browser (( all tabs )) , IE , Firefox working.
But I want to destroy the session when user close the single tab .
I am using :
session_set_cookie_params(0);
session_start();
Browsers only destroy session cookies when the entire browser process is exited. There is no reliable method to determine if/when a user has closed a tab. There is an onbeforeunload handler you can attach to, and hopefully manage to make an ajax call to the server to say the tab's closing, but it's not reliable.
And what if the user has two or more tables open on your site? If they close one tab, the other one would effectively be logged out, even though the user fully intended to keep on using your site.
Solution is to implement a session timeout with own method. Use a simple time stamp that denotes the time of the last request and update it with every request:
You need to code something similar to this
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// request 30 minates ago
session_destroy();
session_unset();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time
More about this you can found here which is similar to your question Destroy or unset session when user close the browser without clicking on logout.
It covers all you need.
this link is very helpfull
But you need to add code to function endsession which is JavaScript function, you can use ajax to call your logout.php. it has worked for me:
$.ajax({
url:"logout.php",
method:'POST',
contentType:false,
processData:false,
success:function(data)
{
alert("session destroyed");
}
});
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.