Destroy PHP Session on closing

前端 未结 5 1633
一生所求
一生所求 2020-11-27 06:35

I have created a simple login page which is based on the sessions.

session_start();

and added a logout page that contains this



        
相关标签:
5条回答
  • 2020-11-27 07:03

    If the session exists, log out by destroying the session and redirecting the user to the home page. A temporary cookie was used to store the session identity. This cookie is also destroyed.

    <?php
        // This is the logout page for the site.
        session_start();//access the current session.
        //if no session variable then redirect the user
        if (!isset($_SESSION['user_id'])) {
        header("location:index.php");
        exit();
        }else{ //cancel the session
            $_SESSION = array(); // Destroy the variables
            session_destroy(); // Destroy the session
            setcookie('PHPSESSID', ", time()-3600,'/', ", 0, 0);//Destroy the cookie
            header("location:index.php");
            exit();
        }
        ?>
    
    0 讨论(0)
  • 2020-11-27 07:16

    You will only be able to detect if the browser window has been closed using javascript at which point you might be able to trigger an Ajax request to perform a logout action.

    0 讨论(0)
  • 2020-11-27 07:18

    to remove session variables - session_unset();

    to destroy the session - session_destroy();

    session_unset();
    session_destroy();
    
    0 讨论(0)
  • 2020-11-27 07:19

    Server can't detect browser or tab closed, you could use Javascript or Ajax but sorry I don't have knowledge about that.

    My suggestion is use Session Timeout, so session will be destroyed if there's no action from user. This is an example :

    // destroy every 2 minutes
    
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
        // last request was more than 2 minutes ago
        session_destroy();   // destroy session data in storage
    }
    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
    
    // end of code
    

    Hope this help you

    0 讨论(0)
  • 2020-11-27 07:28

    if you use:

    session_set_cookie_params(0);
    session_start();
    

    Your session cookie will destroy when the browser is closed... so your session will be good until they close the browser. IE. You login, and you are logged in, you close the browser, re-open it, go to the site again, and you wont be logged in.

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