destroy session when broswer tab closed - php

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");
}
});

Related

How to Force log out php session after x minutes (not inactive log out)

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"

saving session on browser

Is there anyway to destroy session after closing tabs.
if (!isset($_SESSION['access']) || $_SESSION['access'] != 'yes')
{
include("FrontPage.php");
exit();
}
I include this code in some of my application. However it only works when I closes the browser completely. Is this the feature of session or my errors ?
The session cookie is per-process not per window. So even if you
selected New Window you'd still get the same session id. This behavior
makes sense. You wouldn't want a user to re-sign in each time they
opened a new window while browsing your site.
I'm not aware off hand of any real way around this.
Answered by Paul Alexander at Why Doesn't Closing A Tab Delete A Session Cookie?
I guess you could use something in javascript like:
window.onunload
Maybe to call a script destroying the session with session_destroy()

PHP Session issue on browser close

Here running into problem where I have requirement to clear user session when closing the browser. I have tried all the various option like setting session.cookie_lifetime=0 or session_destroy on browser close using onunload function. But nothing seems to destroy session when I open the browser next time.
I just googled a bit and I saw that in Chrome browser there is setting called ''Allow local data to be set' that has to be changed to 'Keep local data only until I quit my browser', when I do this it does not retain my session.
The real problem is I cannot ask each user to change the settings of the browser and then it would work accordingly, is there a way I can handle it in code using php or javascript. Any option is fine.
Have you tried checking for both cookie and session when your page loads? Something like this:
1) destroy cookie on unload
2) on page load check for both
if(isset($_COOKIE['user'] && $isset($_SESSION['user'] {
//user is logged in
} else {
//your code should fall here after user closes browser
//because the cookie doesn't exist anymore. Maybe you can even destroy the session too
[session_destroy();]
...
...
}

How to keep session alive without reloading page?

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

Automatically re-direct a user when session Times out or goes idle

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

Categories