Yii 2 Cookie's Get Not Working

Is there a bug with Yii2 and retrieving a cookie’s value?

I am doing this and it’s returning null:

Yii::$app->response->cookies[‘name’]

I can debug and see that the cookie is set in my browser.


\Yii::$app->getRequest()->getCookies()->getValue('my_cookie');

I haven’t tested it but according to this, it’s the way it should be done.

yii2 have required cookie validation key set in your config…

I do have enableCookieValidation set to true. Do I need to do something else?

Yes,cookieValidationKey.




'request' => [

                    'enableCookieValidation' => true,

                    'enableCsrfValidation' => true,

                    'cookieValidationKey' => 'some_random_key',

                ],



I have cookieValidationKey set already.

How do you set the cookie? Are you checking it in the same request or in the next request?

I am setting it like this:

$cookie = new Cookie([

			'name' => 'itemId',


			'value' => $itemId,


		]);

Yii::$app->response->cookies->add($cookie);

I’m not checking it until the next request.

I’ve tried checking it the following ways:

Yii::$app->response->cookies[‘itemId’]

Yii::$app->response->cookies->getValue(‘itemId’)

Yii::$app->response->cookies->get(‘itemId’)

I have found it is always good to see what Yii is doing itself. So, take a look at the \yii\web\User.php for some hints and direction. It appears to be setting the identity cookie this way:




Yii::$app->getResponse()->getCookies()->add($cookie);



The getResponse() is part of the ResponseEvent class which returns the response object. The Responses getCookies() is your CookieCollection class for that Response and add() is in the Cookie Collection class. The $cookie being passed is a string name of the cookie. It will add it to the cookie collection if not already. The cookie collection is a collection of Cookie class objects.

To get the value it is using:




Yii::$app->getRequest()->getCookies()->getValue($name);



If the $name (string name) exists in the cookie collection, it should return its value or return the default values (null or what is sent as the second parameter of the get value request).

To remove a cookie it uses:




Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));



This can take a Cookie class object or a string name for the removal. There is a removeAll() method if wanted. You can also remove the cookie from the collection but leave it on the browser by sending false as a second parameter.

However look into the code itself on how it works for the Request, Response, Cookie and CookieCollection classes. So getting a value is from the Request class and manipulate the cookies is via the Response class.

thx

94dc27a fixed this. Thanks

I have posted a solution for this question on Stack Overflow. Click here to view it.