简体   繁体   中英

Destroying Session and User Data on browser close ( 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 ie: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM