Destroy database session when user leaves website - php

I am using cakephp 2 and recently changed my session handler to database.
Everything seems to be working fine, except when a user leaves the website without logging out the session is left active.
In my core.php file I have configured database session handler as follows:
Configure::write('Session', array(
'defaults' => 'database'
));
How do I configure cakephp database sessions to destroy the session when a user leaves the site without logging out?
TIA!

You can't. PHP runs on-demand and can't possibly know when a user stops browsing the site. You basically have 2 options:
Write a script to check your session store to find sessions that haven't been accessed in X seconds, and clear them out. Call this script with a cron job.
Check the session when the user comes back, and clear out any stale data. You'll still need to do some cleanup from time to time to get rid of session data from users that never come back.

Sessions are stored on the server, so if the browser is closed or the user goes to a different page, there is no obligation that it informs the server about this action.
Session are stored for a certain time in the server, and after some time of inactivity, it will be destroyed there automatically.
Check Sessions info in CakePHP cookbook for more details

There is a possible solution that will work in some cases but probably isn't a great solution:
<body onUnload="ajaxFunctionToDeleteSession();">
some random stuff goes here
</body>
So ajaxFunctionToDeleteSession would call via Ajax a url that would delete the session.
A few problems with this that I see:
Called anytime someone closes an open page of your site. Which means if someone opens up multiple windows of your site closes one, their entire session, including for the other open tabs is closed
There are probably cases in which someone goes to your site, does something accidentally closes the open window, reopens the site and things will look different because the session is gone.
But if you absolutely must delete a session when someone leaves the site, this may give a way to start approaching the problem.

Related

Invalidate login in Laravel when user leaves the page

It seems a small and easy to solve problem, but I cant find any solution for it.
I want to login the users only for that session while the are browsing the site. As soon as they close the tab I want to make their session expired. As much as I know I can't do this in the built-in Auth class.
How could I do this efficiently?
Short answer: YOU CAN'T
The session can be destroyed when the entire browser is closed by simply setting expire_on_close in config/session.php (also make sure you clear the cookies in your browser for this to work):
'expire_on_close' => true,
But there is no way to detect when only a tab is closed in the browser. The closest thing you would have is the JavasSript method onbeforeunload that triggers when you close a tab. But it also triggers when you navigate away from a page or hit the back button, and there's no way to differentiate between those actions.
You could set a very short session time on the server, and "ping" the server from any open page, to let it know to keep the session still in use, which would mean it would very quickly expire when the tabs that have the app open are closed, but that's an extremely ugly solution.
Since PHP is server side code, it only knows the last time/page that was accessed.
See: Destroy PHP session on page leaving

Site login and session management

So I am working on a site that requires a login against an MySQL database with "remember me" functionality. I got that fine (based off of Jaspan's page). What I am a little fuzzy on is the use of sessions to track user movement. I'm not worried about their history on the site. I've looked around on the interwebs and especially SO, but I haven't really found what I'm looking for. Perhaps I'm just not using the right keywords to search. Anyway... as I said, I have the actual login process, and a cookie is set up with the triplet for the "remember me" functionality. But how do I track the authenticated status while the user is browsing the website? The logged-in user should be able to browse the secure area of the website, or the scripts should output special data, without the website having to check the "remember me" triplet against the database every page load. I thought to do something like $_SESSION['authed']==true, and every page load would check the session value, but I suspect that isn't a very secure way to go about this. I have observed that if I set $_SESSION['authed']==true, close the browser, open the browser, and go to the site again, it still says authed=true. Now, I DO understand that the session variables are stored on the webserver, not in the browser's cache. However, I can't see the big picture enough to know the right way to go about this.
I thought to do something like $_SESSION['authed']==true, and every page load would check the session value
Yes, that's what you do.
but I suspect that isn't a very secure way to go about this
It's perfectly fine. You establish a session, which means you send a unique cookie to the user. That is your security. The fact that you have a session at all is your security. Then you simply record the fact whether the user is "logged in" or not in that session.
I have observed that if I set $_SESSION['authed']==true, close the browser, open the browser, and go to the site again, it still says authed=true.
Yes, cookies don't necessarily expire when the browser is closed. Each cookie has a specified expiration time, they can persist however long you want. Even cookies without an expiration time aren't necessarily immediately discarded when the browser is closed. That may have been the default behaviour of browsers a few years ago, but isn't necessarily true anymore.

php PHPSESSID exists but session destroyed

I am trying to login an user for 2 weeks if user login with remember me check then i have set some variables in session and cookie set for 2 weeks. It is set correctly i have printed it and got the value session_cookie_lifetime = 1209600 and session_gc_maxlifetime = 1209600. I also print session and got correct value in $_SESSION.
After login in my site when i shut down my computer and reopen my site it seems that it is working (it is keeping me as login user). But when i shut down my computer and next day when i open my browser it is not working and it is showing that i am not login on my site. I have printed $_COOKIE and $_session . It shows that in cookie there is :
[PHPSESSID] => svikos35bgclmebk2cqraiddt2
But session is empty.
I got this form modx stuff:
MODx automatically starts and ends sessions with each request made to the site. You can simply save values into the $_SESSION array and they will be saved in between requests so you can use them on subsequent pages (so long as you have the same user session). Not really any magic to it other than don’t call the session functions yourself to start, end, or otherwise manipulate the session configuration—that can all be done via settings in MODx.
I am using modx revo. It is a bit descriptive question. let me know you need something else.
Anything that may help me (blog link,any settings, any suggestion ) will be highly appreciated.
Thanks in advance
This only happens after a day?
Could tmpwatch be deleting session files from the server?
session_cookie_lifetime and session_gc_maxlifetime doesn't garantee you, that session will be saved for a week. GC kill unused sessions. Check PHP documentation about this parameters and you see, that you can't be sure, that your session will be on the server and you don't be sure, that your sesssion will be destroed after this time. GC is async.
You need to recreate $_SESSION after login (and autologin) if it doesn't exists.
Check this article (in russian, try google translate:
PHP GC: unexpected behavior
The basic idea behind SESSION is that, When you create or call session_start() method your server generate a session id and store it on server memory. Also the server create a cookie on your client machine that cookie contains an id that is related to your server side session id. When you call session_destroy() method server delete that id on server side but the client side cookie doesn't. That is why your session id still shown. You can also check by cache and cookie clearing. When you clear cookie your session will destroyed.

FOSUserBundle - Unique session access

Using Symfony 2.0 and FOSUserBundle, I need to know how to restrict the access to make it unique.
This is what I mean:
User X accesses to my system creating a session through login/password
With that session still valid (not having closed the session, etc...), the same user X tries to access from a different computer or location.
In that case, I need the system to avoid its second access with some kind of message: "that user has a valid session from another computer".
Is that possible?
It would be possible and trustable only if you could find a secure way to know when the user session has destroyed or he has logged out from the other computer. As it can occurs without explicit action from the user (i.e. he closed the browser and the session timed out), I wouldn't rely on it. Of course you could always try to find some workaround (i.e. predicate session expiration time and track user logging out) but it still would not be 100% secure. Thinks about cases where new accesses will be denied because a session is still open on another browser without people in front of it.
On the other hand, you can do it the other way (when new user logs in, the other logs out) using Voters and some hints found in Allow one session only at a time.
Correct me if I am wrong, but I think there is finally no way to do what I am trying to since Chrome (and I think FF too) save the exact cookie and are able to restore the session skiping all LoginHandler methods.
Let me explain myself.
Right, I was about (and actually I did) to implement the solution described in your answers and comments:
User X enters the web site with his login/password using Safari (for example)
The login datetime is stored both in table User in the database and in session
Without logging out, the same User X opens a different browser (Chrome, for example)
The new login datetime is updated in database and in Firefox session
The user gets back to Safari and tries to refresh the page
He gets an exception as the datetime doesn't coincide with the one stored in session
Well... great so far, as it seems to solve the problem.
And here comes the big deal: as described here and here, Chrome is not deleting properly the session cookies. So when user doesn't logs out and just close the browser, anytime he or she comes back to Chrome, the session is automatically restored without passing through a login handler, login method or anything around.
This causes that "magical" datetime key not to be saved both in database and session and, as a result, put a stick in the wheel of letting just one session as a time, what was the original plan.
Any more light on the issue??
I want to cry :(

how to make session ends after closing browser

i used a simple session to create a login system,
<?php
session_start();
$_SESSION['username'] = $username;
?>
this is just a part of the code but it is what generate my session , it works fine until now, the problem is that this session don't end with browser closure, i tryed to login the close the browser , but when i visit the website again i find that i'm still logged in, the only way to logout is using a log out system, what i want is an automatic way to close the session on browser's closure, thanks in advance
Simple Answer: You can't. The session exists on the server and the browser exists on the client's machine. The browser does not notify the server when it is closing. In many cases (ex: a computer failure or network disconnect), the browser is unable to notify your server even if it wanted to.
Complex Answer: You could set a very low session timeout time (ie: 5 minutes) and update it every time the user pings the server, but this will log people out if they've been away from their keyboard for more than your timeout time.

Categories