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就可以了