Yii2.0中session有效期设置原理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2.0中session有效期设置原理相关的知识,希望对你有一定的参考价值。
1、session设置方法
$session = Yii::$app->session;
//当session没有值 或 过期时间到 则重新付值
if(!isset($session[‘user‘]) || $session[‘user‘][‘expire_time‘] < time()){
$data = [
‘title‘ => ‘data‘, //数据
‘expire_time‘ => time() + 10, //这里设置10秒过期
];
$session[‘user‘] = $data;
}var_dump($session[‘user‘]);
2、session其他操作:
yii2打开session
use yiiwebSession;$session = Yii::$app->session;
// check if a session is already open
if ($session->isActive) ...
// open a session
$session->open();
// close a session
$session->close();
// destroys all data registered to a session.
$session->destroy();设置session
$session = Yii::$app->session;
$session->set(‘user_id‘, ‘1234‘);
//OR
$session[‘user_id‘] = ‘1234‘;
//OR
$_SESSION[‘user_id‘] = ‘1234‘;读取session
$session = Yii::$app->session;
$user_id = $session->get(‘user_id‘);
//OR
$user_id = $session[‘user_id‘];
//OR
$user_id = isset($_SESSION[‘user_id‘]) ? $_SESSION[‘user_id‘] : null;
销毁session
$session = Yii::$app->session;
$session->remove(‘user_id‘);
//OR
unset($session[‘user_id‘]);
//OR
unset($_SESSION[‘user_id‘]);数组session的读取与设置
$session = Yii::$app->session;
$session[‘user‘] = [
‘id‘ => 1,
‘username‘ => ‘yiiuser‘,
];
echo $session[‘user‘][‘id‘];
echo $session[‘user‘][‘username‘];$session[‘user.id‘] = 1;
$session[‘user.username‘] = ‘yiiuser‘;
ps:
设置session过期时间不起作用,无效。解决办法:
Problem is in cookies expire time. When it timed out, user is logout. Solution, for changing cookies expire time is in configuration for session component set for cookies lifetime:
‘components’ => [
‘session’ => [
‘class’ => ‘yiiwebSession’,
‘cookieParams’ => [‘lifetime’ => 7 24 60 * 60]
],
]
When user login, cookies expire time in current example is after week.
问题在于cookie的过期时间,设置cookie的生命周期时间lifttime就可以了
以上是关于Yii2.0中session有效期设置原理的主要内容,如果未能解决你的问题,请参考以下文章
PHP 分布式集群中session共享问题以及session有效期的设置