PHP - Session destroy after closing browser

前端 未结 9 1389
陌清茗
陌清茗 2020-11-27 07:43

Though this question has multiple duplicates i could not find proper solution for me. Need Some help.

I have used ini_set(\'session.cookie_lifetime\', 0);

相关标签:
9条回答
  • 2020-11-27 08:00

    There are different ways to do this, but the server can't detect when de browser gets closed so destroying it then is hard.

    • timeout session.

    Either create a new session with the current time or add a time variable to the current session. and then check it when you start up or perform an action to see if the session has to be removed.

    session_start();
    $_SESSION["timeout"] = time();
    //if 100 seconds have passed since creating session delete it.
    if(time() - $_SESSION["timeout"] > 100){ 
        unset($_SESSION["timeout"];
    }
    
    • ajax

    Make javascript perform an ajax call that will delete the session, with onbeforeunload() a javascript function that calls a final action when the user leaves the page. For some reason this doesnt always work though.

    • delete it on startup.

    If you always want the user to see the login page on startup after the page has been closed you can just delete the session on startup.

    <? php
    session_start();
    unset($_SESSION["session"]);
    

    and there probably are some more.

    0 讨论(0)
  • 2020-11-27 08:03

    This might help you,

    session_set_cookie_params(0);
    session_start();
    

    Your session cookie will be destroyed... so your session will be good until the browser is open. please view http://www.php.net//manual/en/function.session-set-cookie-params.php this may help you.

    0 讨论(0)
  • 2020-11-27 08:14

    You can do it using JavaScript by triggering an ajax request to server to destroy the session on onbeforeunload event fired when we closes the browse tab or window or browser.

    0 讨论(0)
  • 2020-11-27 08:15

    Use the following code to destroy the session:

     <?php
        session_start();
        unset($_SESSION['sessionvariable']);
        header("Location:index.php");
        ?>
    
    0 讨论(0)
  • 2020-11-27 08:18

    If you are confused what to do, just refer to the manual of session_destroy() function:

    http://php.net/manual/en/function.session-destroy.php

    There you can find some more features of session_destroy().

    0 讨论(0)
  • 2020-11-27 08:19

    The best way is to close the session is: if there is no response for that session after particular interval of time. then close. Please see this post and I hope it will resolve the issue. "How to change the session timeout in PHP?"

    0 讨论(0)
提交回复
热议问题