1. Cookies
Yii2 cookies are operated primarily through yii/web/request and Yii/web/response, through/yii:: $app->response->getcookies ()->add () Add cookies and read cookies via/yii:: $app->request->cookies.
1) Add a cookie
<?php
//The first method
$cookie = New/yii/web/cookie ();
$cookie-> name = ' Smister ';//cookie
$cookie-> expire = time () + 3600;//Live
$cookie-> httponly = True Unable to read cookies through JS
$cookie-> value = ' cookievalue ';//cookie value
/yii:: $app->response->getcookies ()- >add ($cookie);
The second method
$cookie = New/yii/web/cookie ([
' name ' => ' smister ', '
expire ' => time () + 3600,
' HttpOnly ' => true,
' value ' => ' Cookievalue '
]);
/yii:: $app->response->getcookies ()->add ($cookie);
>
2) Read a cookie
<?php
$cookie =/yii:: $app->request->cookies;
Returns a/yii/web/cookie object
$cookie->get (' Smister ');
Returns the value of the cookie directly
$cookie->getvalue (' smister ');//$cookie [' smister '] In fact this is also readable
//To determine whether a cookie exists
$ Cookie->has (' Smister ');
The total number of read cookies
$cookie->count ();//$cookie->getcount (); Like Count
?>
3) Delete Cookies
<?php
$cookie = Yii:: $app->request->cookies->get (' Smister ');
Remove a Cookie object
/yii:: $app->response->getcookies ()->remove ($cookie);
Removing all cookies now seems to be a little too good
/yii:: $app->response->getcookies ()->removeall ();
? >
4) Note
The response that is invoked when a cookie is being added, and when the cookie is read, the request is used
2, session
YII2 session is relatively simple, directly through the/yii:: $app->session To do the operation is good
1) Add a session
<?php
$session =/yii:: $app->session;
$session->set (' smister_name ', ' myname ');
$session->set (' Smister_array ', [1,2,3]);
? >
2 read a session
<?php
$session =/yii:: $app->session;
Read a session
$session->get (' smister_name);
? >
3) Delete session
<?php
$session =/yii:: $app->session;
Deletes a session
$session->remove (' smister_name ');
Delete all session
$session->removeall ();
? >
The above is a small set to introduce the Yii2.0 in the cookie and session usage, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!