1、session設(shè)置方法
創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的安康網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
$session = Yii::$app->session;
//當(dāng)session沒有值 或 過期時(shí)間到 則重新付值
if(!isset($session['user']) || $session['user']['expire_time'] < time()){
$data = [
'title' => 'data', //數(shù)據(jù)
'expire_time' => time() + 10, //這里設(shè)置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();設(shè)置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']);數(shù)組session的讀取與設(shè)置
$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:
設(shè)置session過期時(shí)間不起作用,無效。解決辦法:
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的過期時(shí)間,設(shè)置cookie的生命周期時(shí)間lifttime就可以了