Home  >  Article  >  Backend Development  >  COOKIE and SESSION usage in Yii2.0

COOKIE and SESSION usage in Yii2.0

高洛峰
高洛峰Original
2017-02-06 17:03:271559browse

1. Cookie

Yii2 Cookies are mainly operated through yii/web/Request and yii/web/Response, through /Yii::$app->response->getCookies() ->add() adds Cookie and reads Cookie through /Yii::$app->request->cookies.

1) Add a Cookie

 name = 'smister';//cookie的名称
$cookie -> expire = time() + 3600; //存活的时间
$cookie -> httpOnly = true; //无法通过js读取cookie
$cookie -> value = 'cookieValue'; //cookie的值
/Yii::$app->response->getCookies()->add($cookie);
//第二种方法
$cookie = new /yii/web/Cookie([
‘name' => ‘smister',
‘expire' => time() + 3600,
‘httpOnly ' => true,
‘value' => ‘cookieValue'
]);
/Yii::$app->response->getCookies()->add($cookie);
?>

2) Read a Cookie

request->cookies;
//返回一个/yii/web/Cookie对象
$cookie->get(‘smister');
//直接返回Cookie的值
$cookie->getValue(‘smister'); //$cookie[‘smister'] 其实这样也是可以读取的
//判断一个Cookie是否存在
$cookie->has(‘smister');
//读取Cookie的总数
$cookie->count();//$cookie->getCount();跟count一样
?>

3) Delete Cookie

request->cookies->get(‘smister');
//移除一个Cookie对象
/Yii::$app->response->getCookies()->remove($cookie);
//移除所有Cookie,目前好像不太好使
/Yii::$app->response->getCookies()->removeAll();
?>

4) Note

Perform Cookie The response is called when adding, deleting or modifying. When reading cookies, Request

##2 and Session

are used. Yii2's Session is relatively simple and can be performed directly through /Yii::$app->session. Just do it

1) Add a session

session;
$session->set('smister_name' , 'myname');
$session->set('smister_array' ,[1,2,3]);
?>

2) Read a session

session;
//读取一个Session
$session->get('smister_name);
?>

3) Delete Session

session;
//删除一个session
$session->remove(‘smister_name');
//删除所有session
$session->removeAll();
?>

The above is the usage of COOKIE and SESSION in Yii2.0 introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message. , the editor will reply to everyone in time. I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to COOKIE and SESSION usage in Yii2.0, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn