【PHP】使用session控制同一个账户单设备登陆

首先使用一个浏览器来访问应用的一个页面 multex_session1.php

要记录当前账号所使用的sessionId,使用session_id()获取到当前的sessionId

然后用另一个浏览器和同一个账号访问另一个页面 multex_session2.php

在该页面中会找到该账号之前使用的sessionId,然后清除该sessionId保存的所有内容,然后重新写入session值,并将新的sessionId写入redis中

清除旧的sessionId使用的方法有 session_start()????? ?session_unset() ? session_write_close()

具体代码:multex_session1.php

<?php
    
    $redis = new Redis();
    $redis->connect('192.168.1.102',6379);
    session_start();
    $curSessionId = session_id();
    echo 'sessionId='.$curSessionId.'<br/>';
    $userSession = $redis->get('online:1');
    echo "userSession:{$userSession},user_id:{$_SESSION['user_id']},user_name:{$_SESSION['user_name']}";
 
    $_SESSION['user_id'] = 1;
    $_SESSION['user_name'] = 'areyouok';
 
    $redis->set('online:1', $curSessionId);
    $redis->expire('online:1', 1800);
    session_write_close();

multex_session2.php

<?php
    session_start();
    $curSessionId = session_id();
    echo 'sessionId='.$curSessionId.'<br/>';
    session_write_close();
 
    $redis = new Redis();
    $redis->connect('192.168.1.102',6379);
    $oldSession = $redis->get('online:1');
    if (!empty($oldSession) && !empty($curSessionId) && $curSessionId != $oldSession) {
        echo 'oldSession not equal new sessionId<br/>';
        $redis->set('online:1', $curSessionId);
        $redis->expire('online:1', 1800);
 
        session_id($oldSession);
        session_start();
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            echo 'arrive here,'.json_encode($params).'<br/>';
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        unset($_SESSION['user_id']);
        unset($_SESSION['user_name']);
        session_unset();
        session_write_close();
    
        session_id($curSessionId);
        session_start();    
        echo "oldSession:{$oldSession},user_id:{$_SESSION['user_id']},user_name:{$_SESSION['user_name']}";
        $_SESSION['user_id'] = 1;
        $_SESSION['user_name'] = 'areyouok';    
        session_write_close();
    }

相关推荐