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 yii\web\Session;$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’ => ‘yii\web\Session’,
‘cookieParams’ => [‘lifetime’ => 7 24 60 * 60]
],
]
When user login, cookies expire time in current example is after week.
问题在于cookie的过期时间,设置cookie的生命周期时间lifttime就可以了
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。