1. 程式人生 > >Yii2.0中session有效期設置原理

Yii2.0中session有效期設置原理

lock for isset 其他 sse life one iss yii2.0

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有效期設置原理