一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

yii框架中session的使用方法详解

时间:2022-06-25 00:53:18 编辑:袖梨 来源:一聚教程网

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';

热门栏目