Yii Framework 2.0 Tutorial

Cookies Handling In Yii Framework 2.0

A cookie is a small file that the server embeds on the user's computer and it is often used to identify a user. In plain PHP we can access using $_COOKIE global variable. In Yii, cookie is an object of 'yii\web\Cookie'. 'yii\web\Request' and 'yii\web\Response' maintain a collection of cookies via the property named cookies.

Set Cookies

Using below code we can send the new cookie to the user.


$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',
]));

Get Cookies

We can get get the cookies from the yii app request.

$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');

Remove Cookies

To delete the cookie value, we can use the remove() function of yii.

$cookies = Yii::$app->response->cookies;
$cookies->remove('username');
unset($cookies['username']);