Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: How to read a cookie, which was set by JavaScript

Tags:

yii2

I set a cookie in web/js/site.js:

$.cookie("sidebar", "hidden", { path: '/' });

I read the cookie with PHP:

$sidebar_toggle_state = $_COOKIE['sidebar'];

Is it possible to use also the Yii Request Component to read such cookies? The following code doesn't read the cookie:

$sidebar_toggle_state = Yii::$app->request()->cookies()->getValue('sidebar', '');

See: http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html#cookies

When I set a new cookie through the Yii Response Component:

Yii::$app->response->cookies->add(new yii\web\Cookie([
    'name' => 'sidebar',
    'value' => 'hidden',
]));

Then the value of the cookie looks like this (because the cookie is protected):

3976220a3c8e46bb641aef1da3accfb1652bffd5bb9de503a9d6882e8a69f6f9a%3A2%3A%7Bi%3A0%3Bs%3A7%3A%22sidebar%22%3Bi%3A1%3Bs%3A6%3A%22hidden%22%3B%7D

Such cookie can the Yii Request Component read. But can it read also unprotected cookies?

Or, is it possible to set the Yii protected cookies with JavasSript / jQuery (without using AJAX)?

like image 433
Antonín Slejška Avatar asked Oct 27 '15 08:10

Antonín Slejška


1 Answers

To read a cookie set by Javascript, you have, in configurations, config/web.php to set some request components properties to be false like the following:

'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'SomeRandomStringChars',
            'enableCookieValidation' => false,
            'enableCsrfValidation' => false,
        ],

This will allow reading cookies that have been set using Javascript like the following:

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

Warning!

The above solution may has security issues, because we canceled the enableCookieValidation and enableCsrfValidation for all cookies. So there is another solution that allows jumping those validations for a specific cookie, suppose the theme cookie that we just have used in the example above, we will utilize the second parameter of getValue() method, i.e the default value, like the following:

Yii::$app->getRequest()->getCookies()->getValue('theme', (isset($_COOKIE['theme']))? $_COOKIE['theme']: 'theme')

The above solution will let you keeping both, enableCookieValidation and enableCsrfValidation to be true and only bypass them for a specific cookie.

like image 97
SaidbakR Avatar answered Sep 19 '22 15:09

SaidbakR