Answer the question
In order to leave comments, you need to log in
Problem with cookies in Yii2?
There is a website with companies. The company can be added to favorites and removed. The selected company ID is stored in cookies. On the company page, everything works without problems. The company is added and removed from cookies without problems. But on the page with a list of selected companies, it's just mystic)). After adding a company, it appears on the favorites page either immediately or after the nth number of reloads. Same with removal. An example of work can be viewed on the pages - Company page (cookies work correctly) , Favorites page (cookies work as they want) . Adding and deleting occurs by clicking on the star.
Here is part of the code for setting cookies
$favorite[] = $id; //Идентификатор компании для добавления
$cookies = Yii::$app->response->cookies;
$cookies->add(new \yii\web\Cookie([
'name' => 'favoriteCompanies',
'value' => serialize($favorite),
'expire' => time() + 60*60*24*365
]));
$cookies = Yii::$app->request->cookies;
if ($cookies->has('favoriteCompanies') && $cookies->getValue('favoriteCompanies') != '')
return $cookies->getValue('favoriteCompanies');
else {
return false;
}
$favorite
. The code for handling cookies on both pages is the same. Tell me what could be the problem.Answer the question
In order to leave comments, you need to log in
I don’t see such glitches, everything works fine, it can be removed / added, the bug could not be reproduced (
Googlechrome, Windows 7. Perhaps you have some development extension that is not very gentle with cookies? Try a different browser, ask your friends test the page, most likely the bug is local in nature, if I were you I would store it not in the cookie but in the session, in the hardcore version in the database), but in the cookie just some userkey. I don’t think that a user will come in a year and be like this: “Oh, Christmas trees, I had so many useful things in my favorites!” ) But if you really want to - write to the database, pull it out by key.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question