Destroy Session when leaving the page

Asked

Viewed 1,111 times

-5

I have a system for registering budgets and I need that when the person closes the page, before, display a confirmation message, if they really want to leave the page. If she confirms, destroy the session.

Session I need:

$_SESSION['produtos']
  • Why don’t you define a lifetime specific to the Cookie. If the person closes the browser, the session is already closed.

1 answer

6


The identification of the user’s session is by a cookie - by default, the name of the cookie is PHPSESSID. If the user loses the cookie, he’ll miss the session, just like that.

So, for the session to stay alive only as long as the user has the browser open, you just have to configure to the cookie survive as long as the user keeps the browser open.

At runtime, you can configure this with the function session_set_cookie_params, or you can change your php.ini accordingly:

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )

The first parameter defines the lifetime of the cookie of the session, in seconds. If given the value 0, which is the default, the cookie expires when the browser is closed.

Including, options such as "Remember" during the login usually just set a time other than 0 for the lifetime of the cookie, so it will be persisted in the browser even when it is closed.


As for the confirmation message to close the page, you should do this with Javascript, with no relation to PHP. Something like, for example, listening to the event unload window:

window.onbeforeunload = function() {
    return "Gostaria mesmo de sair?";
};

Credits to Guilherme

Maybe it’s not exactly that, because I tried to reproduce and I couldn’t. I’ll look for more details, but if anyone knows, just let them know that I’ve already edited.

  • 1

    Best option. There’s no reason to complicate this. + 1

  • unload should be exchanged for beforeunload, I believe, and confirm should not be necessary.

  • 1

    Just a detail, onbeforeunload is not to detect closures, in fact I personally consider any scenario thinking of using for something similar a huge problem, since in fact it detects discharges and not closures, related: https://answall.com/a/256171/3635

Browser other questions tagged

You are not signed in. Login or sign up in order to post.