开发者

Destroy PHP Session on closing

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

session_start();

and added a logout page that contains this

session_destroy();

Now when I close the browser/page and reopen it, the values of the session are sti开发者_Python百科ll there.

I want to know how to completely destroy the session on page/browser close.


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.


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.


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


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();
    }
    ?>


to remove session variables - session_unset();

to destroy the session - session_destroy();

session_unset();
session_destroy();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜