M
M
makeloo2016-10-05 22:22:21
Yii
makeloo, 2016-10-05 22:22:21

Yii2 where is the cookie lost when going to another page?

on the page site.ru/site/index I add
a new cookie:

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

    // добавление новой куки в HTTP-ответ
    $cookies->add(new \yii\web\Cookie([
        'name' => 'language',
        'value' => 'zh-CN',
    ]));

after which I go to any other page, and when I try to display the cookie using the command
<pre>
     $cookies = Yii::$app->response->cookies;
     print_r($cookies);

Returns an empty array
yii\web\CookieCollection Object
(
    [readOnly] => 
    [_cookies:yii\web\CookieCollection:private] => Array
        (
        )

)

But with this output method
print_r($_COOKIE);
Still I find my cookie
Array
(
    [advanced-frontend] => d302qt09a66ufpa6h8pf9sbqn1
    [_csrf-frontend] => 45e72fe5c56707ee174e40397a050ee2c05dca4b12a1d928d14256434010de98a:2:{i:0;s:14:"_csrf-frontend";i:1;s:32:"8gj4-V-HDakUKW9E39XMJ6EEcsR6_bDW";}
    [language] => f1dc92de966487919bea9a0e6e5240af52c079c42ef8afbad662ba53fc89a2ffa:2:{i:0;s:8:"language";i:1;s:5:"zh-CN";}
)

Please tell me where is the mistake. Why is the cookie not visible when I try to access it using Yii2?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-10-06
@makeloo

When you go to another page, you send a request to the web server, which contains all the information, including the previously set cookies. But to read cookies, you do not use request, but a RESPONSE from the server (response). Accordingly, the solution to your problem is to use the request object
$cookies = Yii::$app->request->cookies;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question