[Yii2笔记]033 Sessions and Cookies [ 技术分享 ]
说明
学习Yii Framework 2(易2框架)的过程是漫长的,也是充满乐趣的,以下是我学习Yii2框架时对官网英文资料(请参见原文网址)的翻译和代码实现,提供了较完整的代码,供你参考。不妥之处,请多多指正!
原文网址:
http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html
http://www.yiiframework.com/doc-2.0/yii-web-session.html
http://www.yiiframework.com/doc-2.0/yii-web-cookie.html
http://www.yiiframework.com/doc-2.0/yii-web-cookiecollection.html
本文主题:Sessions and Cookies
Sessions
yii\web\Session
//定义session
$session=Yii::$app->session;
$session["mysession32"]="b2343242342";//没有open()之前就可以定义和使用
echo "session:".$session["mysession32"];// session:b2343242342
$session->open();
$session["mysession"]="b";
$session->open();
//检测$session是否已经打开(open),可以open()多次
if($session->isActive){
echo "OK";
}else{
echo "Not";
}
echo "<br>my 1st:".$session["mysession"];//my 1st:b
//关闭$session,可以close()多次
$session->close();
$session["mysession"]="hello";//close()之后仍然可以定义和使用
echo "<br><br>my 2nd:".$session["mysession"];//my 2nd:hello
$session->close();//close()之后,此前定义的session仍然可以读取
echo "<br><br>my2 3rd:".$session["mysession"];//my2 3rd:hello
$session["mysession2"]="NTS";
echo "<br>my2 3rd:".$session["mysession2"];//my2 3rd:NTS
//将$session中的所有数据销毁
$session->destroy();//destroy()之后,此前定义的session不存在了
echo "<br><br>my3 4th:".$session["mysession"];//my3 4th:
$session["mysession3"]="NTSHa";//新定义的数据可以使用
echo "<br>my3 4th:".$session["mysession3"];//my3 4th:NTSHa
测试结果:
/*
session:b2343242342
OK
my 1st:b
my 2nd:hello
my2 3rd:hello
my2 3rd:NTS
my3 4th:
my3 4th:NTSHa
*/
// session常规操作:
$session = Yii::$app->session;
//获取session的三种方式:
$language = $session->get('language');
$language = $session['language'];
$language = isset($_SESSION['language']) ? $_SESSION['language'] : null;
//设置session的三种方式:
$session->set('language', 'en-US');
$session['language'] = 'en-US';
$_SESSION['language'] = 'en-US';
//释放session的三种方式:
$session->remove('language');
unset($session['language']);
unset($_SESSION['language']);
//检测session是否开启
echo "isActive:".Yii::$app->session->isActive;//isActive:1,已开启
echo "isActive():".Yii::$app->session->getIsActive();//isActive():1,已开启
//检测session是否存在的三种方式:
if ($session->has('language')) ...
if (isset($session['language'])) ...
if (isset($_SESSION['language'])) ...
//遍历$session中的所有值的两种等效写法:
foreach ($session as $name => $value){
}
foreach ($_SESSION as $name => $value){
}
//检测session是否开启,使用$_SESSION则必须先开启session_start()
if(isset($_SESSION)){
echo "Session OK<br>";
}else{
echo "Session未开启!<br>";
}
//开启session:使用session_start()
session_start();
foreach ($_SESSION as $name => $value) {
echo "<br>session:".$name."=".var_export($value, true);
}
//开启session的另一种方式,使用open()
//使用文件(默认)之外的其他session存储方式时,必须使用open()
$session = Yii::$app->session;
$session->open();
//以上两句操作,等同于执行了以下语句:
session_start();
多维数组session
从性能和编程角度考虑,不建议使用多维数组session,可以使用一维数组,给变量名添加前缀的方法来解决这类需求。
//使用$_SESSION定义多维数组session
session_start();
$_SESSION['captcha']['number'] = 88;
$_SESSION['captcha']['lifetime'] = 3800;
//或
$session = Yii::$app->session;
$session->open();
$_SESSION['captcha']['number'] = 88;
$_SESSION['captcha']['lifetime'] = 3800;
//使用$session定义多维数组session的多种方法:
$session = Yii::$app->session;
//方法一:
$session['captcha'] = [
'number' => 5,
'lifetime' => 3600,
];
//方法二:
$captcha['number'] = 5;
$captcha['lifetime'] = 3600;
$session['captcha'] = $captcha
//方法三:
$session['captcha'] = new \ArrayObject;
$session['captcha']['number'] = 35;
$session['captcha']['lifetime'] = 3900;
//获取多维数组元素:
echo "<br>2 captcha.number:".$session['captcha']['number'];
echo "<br>2 captcha.lifetime:".$session['captcha']['lifetime'];
//使用$session定义复合元素session
$session = Yii::$app->session;
$session['captcha.number'] = 88;
$session['captcha.lifetime'] = 9900;
//获取复合元素
$sess = Yii::$app->session;
echo "<br>captcha.number:".$sess['captcha.number'];
echo "<br>captcha.lifetime:".$sess['captcha.lifetime'];
//获取复合元素的错误方法:
//echo "<br>captcha.number:".$sess['captcha']['number'];
//echo "<br>captcha.lifetime:".$sess['captcha']['lifetime'];
/*
captcha.number:88
captcha.lifetime:9900
*/
//获取多维数组session元素(在同一页面中)
echo "<br>2 captcha.number:".$session['captcha']['number'];
//实例
$session = Yii::$app->session;
//错误写法
// $session['captcha']['number'] = 5;
// $session['captcha']['lifetime'] = 3600;
//正确写法
$session['captcha'] = [
'number' => 5555,
'lifetime' => 3600,
];
echo "<br>2 captcha.number:".$session['captcha']['number'];
echo "<br>2 captcha.lifetime:".$session['captcha']['lifetime'];
测试结果:
/*
2 captcha.number:5555
2 captcha.lifetime:3600
*/
//获取多维数组session元素(跨页面调用)
$sess = Yii::$app->session;
echo "<br>captcha.number:".$sess['captcha']['number'];
echo "<br>captcha.lifetime:".$sess['captcha']['lifetime'];
测试结果:
/*
captcha.number:5555
captcha.lifetime:3600
*/
$session=Yii::$app->session;
//显示session的数量
echo "Session Count:".$session->count;
//循环显示每个session
foreach($session as $k=>$item){
echo "<br>".$k." : ".var_export($item,true);
}
测试结果:
/*
Session Count:2
__flash : array ( )
__id : '57805a0ee4017ae408000029'
*/
//设置session,"NewRepGroupID"="123"
Yii::$app->session->set("NewRepGroupID","123");
//$_SESSION["NewRepGroupID"]="123";//与上句同效
//使用session
echo Yii::$app->session->get("NewRepGroupID");
echo $_SESSION["NewRepGroupID"];//与上句同效
测试结果:
/*
123
*/
// 自定义session存储(Custom Session Storage): yii\web\Session,默认使用文件进行session的保存,还可以将session存储在以下位置: 1、yii\web\DbSession:将session存储在一个数据表中 2、yii\web\CacheSession:将session存储到缓存中(在缓存组件配置中已定义好的) 3、yii\redis\Sessin:使用redis存储session 4、yii\mongodb\Session:将session存储在MongoDB中
//定义数据库存储session
return [
'components' => [
'session' => [
'class' => 'yii\web\DbSession',
// 'db' => 'mydb', // the application component ID of the DB connection. Defaults to 'db'.
// 'sessionTable' => 'my_session', // session table name. Defaults to 'session'.
],
],
];
//创建一个表用于存储session
CREATE TABLE session
(
id CHAR(40) NOT NULL PRIMARY KEY,
expire INTEGER,
data BLOB
)
/*BLOB常见类型定义:
MySQL: LONGBLOB
PostgreSQL: BYTEA
MSSQL: BLOB
*/
//php.ini
session.hash_function=sha256
//上句配置时,session表应修改为:
id CHAR(64) NOT NULL PRIMARY KEY,
//Flash Data,Flash session单值
$session=Yii::$app->session;
//设置Flash session值//setFlash()
$session->setFlash('postDeleted', 'You have successfully deleted your post.');
\Yii::$app->getSession()->setFlash('error', 'This is the message');
\Yii::$app->getSession()->setFlash('success', 'This is the message');
\Yii::$app->getSession()->setFlash('info', 'This is the message');
\Yii::$app->getSession()->setFlash('error', ['Error 1', 'Error 2']);
//视图中显示错误信息:
use yii\bootstrap\Alert;
if( Yii::$app->getSession()->hasFlash('success') ) {
echo Alert::widget([
'options' => [
'class' => 'alert-success', //这里是提示框的class
],
'body' => Yii::$app->getSession()->getFlash('success'), //消息体
]);
}
if( Yii::$app->getSession()->hasFlash('error') ) {
echo Alert::widget([
'options' => [
'class' => 'alert-error',
],
'body' => Yii::$app->getSession()->getFlash('error'),
]);
}
//获取Flash session值// getFlash()
$session->getFlash('postDeleted')
//检测Flash session值是否存在//hasFlash()
$session->hasFlash('postDeleted')
//注意:无论在哪个页面中,只要调用了hasFlash()或getFlash()后,都将销毁相同键名的Flash session值,再在其他页面中再调用时,将不存在此值。
D:\phpwork\b2b\imall\frontend\views\home-special\list.php
$session=Yii::$app->session;
$session->setFlash('postDeleted','123424');
D:\phpwork\b2b\imall\frontend\views\article\blogList.php
$session=Yii::$app->session;
$a=$session->hasFlash('postDeleted');
echo "have:".var_export($a,true);
D:\phpwork\b2b\imall\frontend\views\article\detail.php
$session=Yii::$app->session;
if($session->hasFlash('postDeleted')){
echo "<br>SEssion6:".$session->getFlash('postDeleted');
}else{
echo "<br>NO Flash";
}
//调用Alert显示Flash session值
if(Yii::$app->session->hasFlash('postDeleted')){
echo yii\bootstrap\Alert::widget([
'options' => ['class' => 'alert-info'],
'body' => Yii::$app->session->getFlash('postDeleted'),
]);
}
//Flash session数组 //addFlash(),向同个键名的Flash session添加多个元素(以数组形式存储) //注意:同一个键名的Flash session,addFlash()和setFlash()不要一起混用。
//使用Flash session数组值,addFlash()添加
$session=Yii::$app->session;
$session->addFlash('alerts', 'You have successfully deleted your post.');
$session->addFlash('alerts', 'You have successfully added a new friend.');
$session->addFlash('alerts', 'You are promoted.');
//获取Flash session数组值,getFlash()后遍历数组
$session=Yii::$app->session;
if($session->hasFlash('alerts')){
$alerts=$session->getFlash('alerts');
foreach($alerts as $alert){
echo "<br>S:".$alert;
}
}else{
echo "<br>NO Flash";
}
Cookies s
Yii用yii\web\Cookie对象来代表cookie。在yii\web\Request和yii\web\Response中各自维护着一个名为cookies的cookie集合。表单中的cookies代表在request中提交的cookie值;Response中的cookies则代表发送给用户的所有cookie。 在应用中,处理request和response的是控制器(controller),所以,cookies可以在controller中读取和发送。
//获取cookie值,方法一:如果不存在,则给默认值'en'
$cookies=Yii::$app->request->cookies;
$language=$cookies->getValue('language','en');
echo 'lan2:'.$language;
//获取cookie值,方法二:
$cookies=Yii::$app->request->cookies;
if (($cookie = $cookies->get('language')) !== null) {
$language = $cookie->value;
}else{
$language = 'zh-CN';
}
echo 'lan2:'.$language;
//获取cookie值,方法三:
$cookies=Yii::$app->request->cookies;
//if ($cookies->has('language')) {//与下句同效
if (isset($cookies['language'])) {
$language = $cookies['language']->value;
}else{
$language = 'zh-CN';
}
echo 'lan6:'.$language;
//设置cookie值:
$cookies = Yii::$app->response->cookies;
$cookies->add(new \yii\web\Cookie([
'name' => 'language',
'value' => 'en',
]));
//设置cookie值(完整参数):
$cookies->add(new \yii\web\Cookie([
'name' => 'language',
'value' => 'en',
'domain' => '',
'expire' => 0,//0,until the browser is closed
]));
//删除cookie:
$cookies->remove('language');
//unset($cookies['language']);//与上句等效
//$httpOnly,默认值:true,只能通过http获取cookie,而不能使用客户端脚本(如javascript等)获得cookie(此功能需要浏览器支持) yii\web\Cookie::$httpOnly=true;
// CookieValidation,cookie校验,默认值:true,将为每个在客户端存储的cookie增加一个校验hash码,如果cookie数据被修改,则校验失败。 yii\web\Request::$enableCookieValidation=true; // CookieValidation功能生效,需要在配置中添加cookieValidationKey D:\phpwork\b2b\imall\backend\config\main-local.php
return [
'components' => [
'request' => [
'cookieValidationKey' => 'WnlcOy3JJXwEA73sI-m41UPiLsSBhGI7',
],
],
];
(全文完)
共 0 条回复
阿江
最后登录:2024-03-03
在线时长:186小时21分
- 粉丝94
- 金钱16816
- 威望160
- 积分20276