php中if ($_session['u_id']){,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

$redis = new Redis();

$redis->connect('192.168.1.102',6379);

session_start();

$curSessionId = session_id();

echo 'sessionId='.$curSessionId.'
';

$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

session_start();

$curSessionId = session_id();

echo 'sessionId='.$curSessionId.'
';

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
';

$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).'
';

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值