What I want is to be able to delete session data without page refresh.
So let's say my user created a session and left his computer on sleep mode for two years, I want to delete his session after 4800s...
How can I do that?
At the moment, I have a code which only deletŠµs session on refresh only.
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 4800)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Or does this code work without page refresh?
If not, how can constantly update this code?
Just add this code anywhere in your page
<script type="text/javascript">
setTimeout(function(){
location = ''
},60000)
</script>
reference: Refresh Page for interval using js
100% Working Just Add This Code Once
setTimeout(function () {
window.location.href = "";
}, 3000);
Related
I already had some research and i found a functional code to logout upon inactivity, but my problem is i still need to refresh my browser inorder to prompt my alert function to be able to logout it. I want a code function that will automatically log you out even if you won't do anything. BTW this is my code.
<?php
if (time() - $_SESSION['timestamp'] > 30) {
?>
<script type="text/javascript">
alert("You Have Been inactive for 30 seconds");
window.location.href = "logout.php"; //To my logout function
</script>
<?php
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
?>
pretty easy.
if you have a file that you include in each page you can implement it by adding the refresh script eg
header("Refresh: 1200; url = logoutsess.php");
this will redirect to a file logoutsess.php after 20mins therefore killing the session
It's not possible without refreshing, at least not with PHP.
Have you considered the use of AJAX for this instead of refreshing the browser every 30 seconds.
xhr requests verify_session.php and verify_session.php will check if the user has done anything within the last 30 seconds and print 1 or 0, your JavaScript will then redirect the browser to logout.php if it detects 0.
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 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 javascript code that basically displays a box that says that you will be logged out within 60 seconds if you dont click on the link. Now my question is can I use that link with a JavaScript onClick event to somehow update my php code that detects if your session is older than 30 mins.
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minates ago
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
header("location:login.php");
}
Short of refreshing the includes.php file is there anything else that I can do to update my $_SESSION['LAST_ACTIVITY'] variable?
You'll have to use ajax
I'd suggest you to use jQuery for that.
$("#link").click(function(){
$("#result").load('check.php');
});
To update variable, use
$_SESSION['LAST_ACTIVITY'] = time();
you can use session_cache_expire(); and put that before session_start();
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.