Yii2使用(设置,获取,删除)cookie的方法

  •   
  • 8670
  • PHP
  • 28
  • super_dodo
  • 2016/10/09

Yii2设置Cookies

use yii\web\Cookie;

//使用Cookie类
$cookie = new Cookie();
$cookie->name = 'user_name';
$cookie->value = 'dodobook';
$cookie->domain = '.dodobook.net';			//域名
$cookie->expire = time() + 86400 * 7;		//7天时间
$cookie->httpOnly = true;					//将cookie设置成HttpOnly是为了防止XSS攻击窃取cookie内容,这样就增加了cookie的安全性
$cookie->path = '/';
\Yii::$app->response->cookies->add($cookie);

//另外一种方式
$cookies = Yii::$app->response->cookies;
// add a new cookie to the response to be sent
$cookies->add(new \yii\web\Cookie([
    'name' => 'username',
    'value' => 'yiiuser',
]));

Yii2获取 Cookies

$cookies = Yii::$app->request->cookies;

// get the cookie value 
$username = $cookies->getValue('username');

//return default value if the cookie is not available
$username = $cookies->getValue('username', 'default');	

// Check the availability of the cookie
if ($cookies->has('username')){
	echo $cookies->getValue('username');
}

Yii2删除 Cookies

$cookies = Yii::$app->response->cookies;

$cookies->remove('username');

unset($cookies['username']);

补充一下cookie的httpOnly的知识:将cookie设置成HttpOnly是为了防止XSS攻击窃取cookie内容,这样就增加了cookie的安全性,即便是这样,也不要将重要信息存入cookie。在实际使用中,我们可以使FireCookie查看我们设置的Cookie 是否是HttpOnly。

可以利用HttpResponse的addHeader方法,设置Set-Cookie的值 cookie字符串的格式:key=value; Expires=date; Path=path; Domain=domain; Secure; HttpOnly