我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

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


新闻名称:Yii2.0中session有效期设置原理
标题URL:http://mswzjz.cn/article/jgpppg.html

其他资讯