A
A
AlexAll2020-05-19 22:22:15
Yii
AlexAll, 2020-05-19 22:22:15

How to set cookies in yii2 once if there are several requests at once?

Site on yii2, at the same time another site accesses it, with two or more requests. Naturally, there are no cookies in the requests, and I try to set a cookie, and before installing I check if there is a cookie

$cookies = Yii::$app->request->cookies->getValue('name');


And when more than one request comes at once, naturally, the check does not give anything and the cookie is set (reinstalled) as many times as requests come in and the value for it is set on the last request.
value is made from
md5(microtime() . rand(0, 1000) );
so it is different
How to make it set only on the first request and ignore the rest?

I repeat, I go to the site, three requests are sent at once to load three blocks, and at the reception in the backend I try to set the cookie ONCE, but before that I check for its existence. Since the requests came at the same time, there are no cookies in their headers and the check does not help, there is nothing there and therefore the cookie is assigned several times

public static function setCookies(){
        $cookies = Yii::$app->request->cookies->getValue('name_cookie');
        if(!$cookies){
            $set_cookies_date = (new DateTime())->modify('+1828 day')->format('d.m.Y H:i:s');
            $ip = Yii::$app->request->userIP;
            $hash = md5(microtime() . rand(0, 1000) . $ip);
            $set_cookies = Yii::$app->response->cookies;
            $set_cookies->add(new \yii\web\Cookie([
                'name' => 'name_cookie',
                'value' => $hash,
                'domain' => 'site.local',
                'expire' => strtotime($set_cookies_date),

            ]));
            
        }

 
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Derepko, 2020-05-19
@xEpozZ

Check if there is a value for this cookie, and if not, then do not set.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question