-1

I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox. Following is the examples I tried along with links, My sample Code

<script type="text/javascript">
var str = 'delete';// this will be set to 'Apply' if the form is submitted.
function logout(){
    location.href = 'Logout.php';
}
function pageHidden(evt){
    if (str==='delete')
        logout();
}

    window.addEventListener("pagehide", pageHidden, false);
    </script >

Examples I tried....

// 1st approach
//window.addEventListener("beforeunload", function (e) {
///   var confirmationMessage = "Do you want to leave?";

//    (e || window.event).returnValue = confirmationMessage; 
    //  return confirmationMessage;                            
//  });

// 2nd approach
     //  window.onbeforeunload = myUnloadEvent;
     // function myUnloadEvent() {
     //     console.log("Do your actions in here")
     //  }
// 3rd approach

$(window).on('beforeunload', function() {
  return 'Your own message goes here...';
});

checked the following urls 1. window.onunload is not working properly in Chrome browser. Can any one help me? 2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well. 3. I can't trigger the unload event in Chrome etc....

Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.

Community
  • 1
  • 1
Jag
  • 9
  • 5
  • 2
    "*Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.*" I think you might be trying to solve the wrong problem. There are all kinds of scenarios where you might not get a clean window close event. For example, killing the process, power/internet outage or placing a lit quarter stick of dynamite under the laptop. – JDB Mar 30 '17 at 02:55

2 Answers2

0

You shouldn't rely on JavaScript for sever-side code. It's actually entirely possible to achieve what you're looking for, purely with PHP. Just make sure to 'kill' the session before starting it:

session_set_cookie_params(0);
session_start();

session_set_cookie_params(0) will tell the browser that any exisiting session should only exist for another 0 seconds. Essentially, this means that a user will automatically 'log out' immediately. This way, you don't have to rely on client-side code, which is susceptible to all measure of interrupts such as power outages.

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
  • Hi, My Issue is I should delete the user entry from DB when the user closes the browser/tab by clicking on the X button which is on the right hand top corner. Basically notify php of the user-action, but if I kill the session how does it notify php that the user has closed the browser, if you can provide an example that would be great. we only store the username in DB just to avoid any other user from any-other machine doesn't login(not even from the same machine using a different browser) and also for some other purposes. – Jag Mar 30 '17 at 03:28
  • Why do you need to delete the user entry from the database when the user logs out? They would never be able to log in again (without registering again), so what's the point in having a 'login' system in the first place? There's (highly likely) no harm in not deleting the user from the database. With the above code, the user will essentially be logged out on window close, but in order to trigger a database change on a user closing a window, the **only** way you can do this is with JavaScript, as you have already done. However, this has the interrupt issue, which you will never be able to avoid. – Obsidian Age Mar 30 '17 at 03:37
  • User Authentication is done on a different server once he is authenticated, I am just storing the id, based on some requirement, which should be deleted when the user logsout, I am not completely deleting him from the system. – Jag Mar 31 '17 at 04:09
  • **Why** though? How does your `ID` correlate to the database? You need to copy all user info across; authentication requires both a username and password to be stored in a cookie or `$_SESSION`. If you're **just** storing an ID, you must be doing so through JavaScript, which is certainly the wrong way to handle authentication, as it wouldn't even persist across multiple pages. The `ID` of the logged-in user should be stored in a `$_SESSION` variable -- Which would automatically log them out by writing `session_set_cookie_params(0);` on the page. – Obsidian Age Mar 31 '17 at 04:38
0

The correct way to logout is related to how they are logged in.

In PHP, the login state is typically managed by sessions. By default the timeout is 24 minutes of inactivity, but you can easily reduce it.

When a user logs out, you typically reset one or more session variables, and, while you’re at it, kill off the current session, and delete the session cookie.

However, you cannot rely on a user to log out, and many typically just wander off. This is why there is always a relatively short timeout on sessions.

If you want to automatically logout when the tab is closed, you will need JavaScript to intercept the process with window.onbeforeunload and then use Ajax to send the logout to the server.

As regards the database, you normally do not record the login state in the database. You may record the login time, and if you like, the logout time, but remember that may be never.

Manngo
  • 14,066
  • 10
  • 88
  • 110
  • the logout.php file handles all the cleaning up, such as cleaning session variables, db connections etc. I need to call this page somehow on a window is closed. **bold** 'window.beforeunload' is not being recognised by some browsers. – Jag Apr 13 '17 at 01:19
  • Have you tried without jQuery: `window.onbeforeunload=function(e) { alert('bye bye'); };` If that works, you can replace the alert with your Ajax Logout. – Manngo Apr 13 '17 at 01:45
  • Thanks for a quick response, i tried but unfortunately its failing in some of the browsers. – Jag Apr 13 '17 at 05:15
  • Which browsers? – Manngo Apr 13 '17 at 05:15
  • chrome Version 57.0.2987.133. Also on Firefox – Jag Apr 13 '17 at 05:47
  • Sorry, `alert` is one thing you can’t do in `beforeunload`. Try this: `window.addEventListener('beforeunload',function(e) { var message='bye bye'; /* do Ajax Logout */ e.returnValue = message; return message; });` The two statements at the end will show the prompt, so, when you are satisfied that it’s working, you can remove them. – Manngo Apr 13 '17 at 08:03