Friday, 13 January 2017

Cookies Handling In Yii2 set and get

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

GET COOKIE

$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 COOKIE

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


No comments:

Post a Comment