0

Is there a way to call a php script when the browser or window is closing, when someone hits the X.

I have a login, logout script

$sql2 = "UPDATE `users` SET `loggedin` = '1' WHERE `username` = '$username' AND `password` = '$password' LIMIT 1 ";

that changes an SQL variable to 1 or 0 letting me know if that person is logged on.

if that variable is 1 and someone else tries to login they wont be able to.

but my issue is if someone closes the window without logging out. The variable stays as 1, and therefore they can't log in.

MikeB
  • 2,402
  • 1
  • 15
  • 24

2 Answers2

0

First of all you need to think about having prepared statements since your code is vulnerable to sql injection as of now.

As of answer to question try the following:

  1. use sessions since you need to catch event of browser closing, session lives till browser is open.
  2. If not sessions use javascript to catch closing event (google how to do it) and then send ajax request to PHP script that will update desired fields in DB
GGio
  • 7,563
  • 11
  • 44
  • 81
0

As an addition to GGio;

Use something like this jQuery (JS) function

$(function () {
  $("a").click(function {
    window.onbeforeunload = null;
  });
});

In that function make an AJAX call. When call is made and the browser closes, the server will still process it only have no client to send it back to.

So be careful about the code you put in there, as you cannot check output or ask validation from the user.

More info:

jQuery.ajax on onbeforeunload event not working

http://eureka.ykyuen.info/2011/02/22/jquery-javascript-capture-the-browser-or-tab-closed-event/

http://zeeshanumardotnet.blogspot.co.at/2011/01/how-to-end-session-when-browser-is.html

Community
  • 1
  • 1
mvbrakel
  • 936
  • 5
  • 16
  • What happens when the user does not have javascript enabled. – user1704555 Feb 04 '13 at 23:17
  • Nothing will happen. But take a moment to check you statistics and do a reality check on the work needed to catch and the percentage of your visitors that does not have JS. – mvbrakel Feb 04 '13 at 23:19
  • If you want to go for a non JS solution you would need to have a lifetime on the loggedIn flag. Like set a lastActivity column and update that every time a page loads for that user. Clear the logged in after 5 min of no activity by running something like a (lazy man's ) cron – mvbrakel Feb 04 '13 at 23:21