Destroying Session and User Data on browser close ( PHP) - php

I know this question have been asked lot of times that how to track online users on a site using php , what i do is very basic if a user is logged in to my site i save their data to a database and once they click logout i destroy their session and delete that username from my database.
The real problem occurs when a user directly close the browser coz than i have no way to run a mysql query to my database and looks like they are still logged in though they are not.
I don't want to set any time to destroy cookies or sessions because that is not the appropriate way to do it let say i set time to 30min and a user closed the browser in just a min , so for 29 min he will appear online so i don' t want that.
Thanks

Use web-socket i.e.: http://html5demos.com/web-socket when your user closes the browser, the connection will be interrupted, then you set it as offline, but will only work on modern browsers.
However you still can do something like web-socket using push-stream to monitor your users.
But, if you use sessions, you can setup your timer diconnect to the same time that the session disconnects. PHP is 15 minutes as default (you can customize). So if your user keep your site open by this time but don't make requests, after this time, his session will be closed, even if the browser still open.

There is better solution, use JavaScript to send an AJAX request to your server on "onBeforeUnload" event. This way the script will ensure the session and DB record are only deleted when the user is leaving the website.
<script type="text/javascript">
$(window).on('beforeunload', function() {
$.ajax({
url: /controller/action/clear
});
});
</script>

you must store also time when user was reload page. after authentication, after click some link or something else, you must store/update in database all this actions.
after this, you should check that, if user was visit on site or was reload page about 15 minute ago, that he is not online.

Related

How to allow only one session per user?

I am making a platform where you can only access one session per person, to do this, I had to insert in the DB a session id, then, for example:
The user logs in Chrome, at the time of login, in my DB the session id is inserted.
If the same user logs in Firefox, a new session id is inserted, and at the end it compares which was the last id so that only the last person who logged in can have access.
But the problem I have is that, if the user who logged in in Chrome does not make any movement, ie reload the page or click on another, then it stays right there and does not close the session. What I want to do is that when the user logs in on another device or browser, it automatically bounces the first session.
I know that with JS I can call that block of PHP code where I have the validation every certain time, but this would not work 100% because the platform is courses (videos) so if I make the function to run every 5 min example then you can see a course without problem the other person and if I run every 10 seconds I fear that as it sends many requests at once, you have problems with the server. Another question I have is that if I use JS and I set the function with JS then a user who has some knowledge can inspect and delete the JS and then the set code would not be executed or yes?
A more understandable example is what WhatsApp does not let in theory open another session at the same time. Any idea how to solve? Thank you very much.

Removing users session from mysql table if they click close on browser

I have a descent set up going for a user logging in and theres a session time() and a few other things added to a table.
The issue i have is that when the user closes the browser it dosent delete the session from the mysql table.
From the users perspective its fine because they have to login again when they open the browser.
But for the super-users dashboard it still shows the user is logged in if they close the browser.
I did have a look at the close browser alert javascript code but i would rather find a way doing it without that.
I then thought maybe a cron script but that could log a user out unless i was updating the time() each time they clicked another page. Is that the only way?
I wouldn't trust the browser telling you it was closing.
The only way is to do it on the server.
Try recording the current time against the session every time it gets validated - this will be the sessions last access time.
Then you can remove all sessions that exceed some time period you've decided on. You can either do this via a cron job, or add it to the session validation code and every user can help keep the table tidy.
can your database not have a "isLoggedIn" column. Can it just have a "lastActivityTime" column. The user is logged out if currentTime - lastActivityTime < loggedOutTime

PHP session time out on browser open

I know there are many threads regarding PHP sessions while ajax queries etc...
but my problem is,
I have an ajax grid (build after the page load), which I allow to edit only when use is logged on. I don't mind for session to be not checked until user actually change the page (then valid_session.php is called),
but I have an issue, when next day user opens the browser on the same page - the grid is still editable! obviously if I refresh the page, then user get logged out.
I have no-cache set on my pages, but browsers (in particular chrome) don't reload it on open.
I can't get my head around as how to force it to refresh on reopen. please guide me to the right direction...
EDIT
BTW - I found a way to handle this. I simply call session_destroy(); in session_destroy.php on unload() via $.get():
$(window).unload(function() {
$.get('session_destroy.php', function(data) {
alert(data); // alerts me of some var set to 0 - meaning session is destroyed.
});
});
To log out the user actively i think you should do some kind of polling and then trigger a logout automatically when the session expire. Or print an error message like "Changes done to this page will not be saved as the session has expired".
Obviously the grid can't now "By magic" that the session has expired, you have to tell it somehow. In any case even if the grid it's still editable, it shoul dbe impossible to save changes, otherwise there is a design flaw (like not checking if the user is logged in before saving)
One solution is to set a "last refreshed" cookie, and have a javascript setInterval() which checks if the cookie is older than, say 20 minutes. If it is, the javascript triggers a refresh. Of course, you still need to log them out after the inactivity period.

Check if user is offline

I have an online game. I wish to show how many user are online. The problem is to know when a user is offline.
Is there a way to perform a check on sessions cookie to acknowledge whether the session with the broswer was closed?
I was thinking about simply set a timeout on the server which launch a script that count how many session cookie are present, but how do I check if the session cookie is about somebody who's logged and not just a visitor?
How did you handle this?
1) I don't want to rely on a script fired with the logout button, since nobody ever logout... people simply close the browser.
2) About timestamps and registering activity? Since in my game users interact with an svg (not moving through pages), they generate a huge amount of clicks. Making a query for each click for each of them refreshing a record would be very expensive.
When the user interacts with the site, set their last activity time.
If it is longer than 30 mins or so, you can assume they are offline.
You can also explicitly set someone to offline when they click logout.
However, your case is a little different. You could use a heartbeat style script.
Whilst they are on the page, use setInterval() to extend the expiry date, up to a maximum range (in case the user leaves their browser window open for hours on end).
Since your code gets executed when the page is loaded you cannot make a check if the user closed his browser or not.
So the common approach would be to use timestamps and update this stamp if the user does something on your site and if the timestamp is older than say 5 minutes you just assume he is offline

Login, logout and duration time in php and mysql?

I would like to store the login, logout and duration time in database.
The login time is created when the user is authenticated(successfully logged in)
The logout time is created when the user clicks the logout button
The duration is logout - login time. (logout minus login)
But the problem is, what if the user didnt click the logout button. Here are the situations:
Internet loss
Close the browser/tab. (I need this must use javascript, but i donnu how to do it, any idea?)
EDIT:
I forgot to add something to the question, the program is a full flash program, there is no navigation to other page. Only 1 page
It's important to remember that all session/log-in functions in PHP are usually cookie based. So, changing the lifetime of the session cookie should solve your problem:
http://us3.php.net/manual/en/function.session-set-cookie-params.php
Also, you can set the PHP sessions so they only use cookies:
http://us2.php.net/manual/en/session.configuration.php#ini.session.use-only-cookies
Again, you can catch the browser window / tab close but ... why? For instance I may have your site open in multiple tabs. If I close one of those tabs should I automatically be logged out of your website? That's a very bad design. Instead, set the session lifetime so it expires if the browser is closed and not just a tab. (Note also that window.unload will logout when any window on your site that closes - including a pop-up or an iframe. Do you really want that?)
http://us2.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime
If you want to store session state in a database try any one of these guides. Or, roll your own with session_set_save_handler
You can't rely on receiving an event for the user logging out, if they simply close their browser, or disappear from the internet.
In this case you'll have to have a session timeout of some kind, and record the logout when your app realises their session is too old.
If this is a real requirement, then I'd say you need a "cron" job monitoring the sessions for timeout. When a session has timed out, if the were logged on, it then records a "logout" event for that user.
Note that you can't use (for example) ASPNET's Session_End event, because that won't be reliably called either (for example if the server process restarts).
Another option is to add the logout time next time that user logs on - when they log on, you check for old sessions and assume that any which weren't closed lasted for a fixed amount of time since the last page hit.
That's really all you can do.
Regarding the closing of browser/tab, you can bind the unload event (window.onunload, jQuery's $(window).unload(fn), or any other) to notify your server. A more general purpose solution would be to periodically ping your server (say, every 5 min), but it might be annoying to the user, so do so judiciously.

Categories