本文概述
- 设置 cookie
- 获取 cookie
- 删除 cookie
在Yii中, 每个cookie都是yii \ web \ Cookie的对象。
yii \ web \ Request(请求中提交的cookie的集合)和yii \ web \ Response(需要发送给用户的cookie的集合)通过名为cookies的属性维护cookie的集合。
控制器在应用程序中处理cookie请求和响应。因此, 应在控制器中读取并发送cookie。
设置 cookie 使用以下代码将Cookie发送给最终用户。
// get the cookie collection (yii\web\CookieCollection) from the "response" component
$cookies = Yii::$app->
response->
cookies;
// add a new cookie to the response to be sent
$cookies->
add(new \yii\web\Cookie([
'name' =>
'name', 'value' =>
'sssit', ]));
获取 cookie 要获取Cookie, 请使用以下代码。
// get the cookie collection (yii\web\CookieCollection) from the "request" component
$cookies = Yii::$app->
request->
cookies;
// get the cookie value. If the cookie does not exist, return "default" as the default value.
$name = $cookies->
getValue('name', 'default');
// an alternative way of getting the "name" cookie value
if (($cookie = $cookies->
get('name')) !== null) {
$name = $cookie->
value;
}// you may also use $cookies like an array
if (isset($cookies['name'])) {
$name = $cookies['name']->
value;
}// check if there is a "name" cookie
if ($cookies->
has('name')) ...
if (isset($cookies['name'])) ...
删除 cookie 【YII cookie介绍和用法示例】要删除cookie, 请使用Yii的remove()函数。
$cookies = Yii::$app->
response->
cookies;
// remove a cookie
$cookies->
remove('name');
// equivalent to the following
unset($cookies['name']);
例:
让我们看一个设置和显示cookie值的示例。
步骤1在SiteController.php文件中添加两个动作actionSetCookie和actionShowCookie。
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' =>
[
'class' =>
AccessControl::className(), 'only' =>
['logout', 'signup'], 'rules' =>
[
[
'actions' =>
['signup'], 'allow' =>
true, 'roles' =>
['?'], ], [
'actions' =>
['logout', 'set-cookie', 'show-cookie'], 'allow' =>
true, 'roles' =>
['@'], ], ], ], 'verbs' =>
[
'class' =>
VerbFilter::className(), 'actions' =>
[
'logout' =>
['post'], ], ], ];
} /**
* @inheritdoc
*/
public function actions()
{
return [
'error' =>
[
'class' =>
'yii\web\ErrorAction', ], 'captcha' =>
[
'class' =>
'yii\captcha\CaptchaAction', 'fixedVerifyCode' =>
YII_ENV_TEST ? 'testme' : null, ], ];
} public function actionSetCookie()
{
$cookies = Yii::$app->
response->
cookies;
$cookies->
add(new \yii\web\Cookie
([
'name' =>
'test', 'value' =>
'SSSIT Pvt. Ltd.'
]));
} public function actionShowCookie()
{
if(Yii::$app->
getRequest()->
getCookies()->
has('test'))
{
print_r(Yii::$app->
getRequest()->
getCookies()->
getValue('test'));
}
}
步骤2在浏览器上运行它, 以首先使用以下URL设置cookie,
http://localhost/cook/frontend/web/index.php?r = site / set-cookie
文章图片
步骤3在浏览器上运行它, 以显示具有以下URL的cookie,
http://localhost/cook/frontend/web/index.php?r = site / show-cookie
文章图片
推荐阅读
- YII控制器动作介绍和用法示例
- YII控制器介绍和用法示例
- Yii CRUD数据库操作实例图解
- Linux安装YII详细步骤图解(最全面)
- Yii2快速安装简要步骤
- YII教程入门介绍
- Yii项目结构详细解释
- 使用Charles对Android App的https请求进行抓包
- Android ANR 分析