Jan
Jan

Reputation: 63

Destroying a session when user closes tab or window

I want te destroy a session when the users close the tab or window without logging out properly. And I thought this might work:

the javascript:

$(window).on("beforeunload", function(){
    alert("Beforeunload called");
    $(document).load("vve_inc/php/vve_logout.php");
});

the php:

<?php
session_start();
session_destroy();
?>

The alert works fine, but the php-script doesn't. Has anybody got any idea's?

Upvotes: 1

Views: 1095

Answers (2)

Rob M.
Rob M.

Reputation: 36511

qwuertynl is correct, however you can use ignore_user_abort(); in PHP and it will not matter if the AJAX request completes or not. I have successfully used this at large scale in the past.

http://php.net/manual/en/function.ignore-user-abort.php

Calling that function will make your PHP script run to completion, regardless of whether or not the request is aborted.

Upvotes: 0

qwertynl
qwertynl

Reputation: 3933

The alert stops execution of the code.

Doing an AJAX request on unload is unstable and will not always be executed.

It would be better if you just had a logout button or a session timeout.

Upvotes: 1

Related Questions