How to detect if a user has logged out, in php?

后端 未结 12 2468
南笙
南笙 2020-12-06 02:19

After the user successfully logs in, I store login = true in database. But how do I check if the user logged out by closing the browser without clicking the logout button? A

12条回答
  •  执笔经年
    2020-12-06 03:22

    Store the timestamp of each acitivity of the user. When that time is more than 10 minutes ago, do the logout.

    In PHP, you could do something like this:

    session_start();
    if (!isset($_SESSION['LAST_ACTIVITY'])) {
        // initiate value
        $_SESSION['LAST_ACTIVITY'] = time();
    }
    if (time() - $_SESSION['LAST_ACTIVITY'] > 3600) {
        // last activity is more than 10 minutes ago
        session_destroy();
    } else {
        // update last activity timestamp
        $_SESSION['LAST_ACTIVITY'] = time();
    }
    

    The same can be done on the database instead. There you could even get a list of users that are “currently” online.

提交回复
热议问题