简体   繁体   中英

php session keep alive to check activity

I read around that there is a way to keep checking every 30sec or so if the user is still active on the website and if not, logout (or do something else)

I have a basic inactivity logout but it only works if the user is on the website, but if the user closes the browser/tab, it won't work

    if (isset($_SESSION['time'])) {
        $elapsed_time = time() - $_SESSION['time'];
        if ($elapsed_time >= 900) {
            mysql_query("UPDATE `users` SET `status` = '0' WHERE `user_id` = '$session_user_id'");
            session_destroy();
            header('Location:index.php');
        }
    }
    $_SESSION['time'] = time();

how can i do it so that the status changes to 0 only after X amount of inactive time (but it doesn't necessarily have to log the user out - just change the status)?

hook the session save handler functions, specifically the garbage collection one.

While the below examples show deleting, you could easily modify it to just set an inactivity flag, which can then be read from your inactivity script.

session_set_save_handler docs

PHP <5.4 From: http://www.sitepoint.com/writing-custom-session-handlers/

session_set_save_handler("open", "close", "read", "write", "destroy", "garbage");
function gc($lifetime) {
    $db = new PDO("mysql:host=myhost;dbname=mydb", "myuser", "mypassword");
    $sql = "DELETE FROM session WHERE session_lastaccesstime < DATE_SUB(NOW(), INTERVAL " . $lifetime . " SECOND)";
    $db->query($sql);
}
//below ones are covered in the article.
function open(){}
function close(){}
function read(){}
function write(){}
function destroy(){}

Php 5.4+ From: http://www.php.net/manual/en/class.sessionhandlerinterface.php#example-4769

Note: this example is file based you would just have to modify it to use database

<?php
class MySessionHandler implements SessionHandlerInterface
{
    public function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
    //below functions are covered in the manual
    public function open($savePath, $sessionName){}
    public function close(){}
    public function read($id){}
    public function write($id, $data){}
    public function destroy($id){}
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

Both rely on a good number of users visiting your site. Otherwise if for instance you dont get users for days the like garbage collection function will not be run for days. In cases like that you would have to setup some other system like a cron job to trigger a script every so often.

Delete the files with the following cron:

find .session/ -amin +20  -exec rm {} \;

This will delete session files that have not been accessed for 20 minutes. This will delete all PHP sessions, assuming you are the only person on the server.

More ways to do this are specified in this question: cleanup php session files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM