2 years ago

#43400

test-img

ScreamX

Simultaneous writing to cookies

Stupid question, but still relevant. The thing is that I record the products that the user has viewed (in cookies).

If you open two pages at the same time, then getList will get the same list and simply overwrite the other product that opened with it at the same time.

It doesn't occur to me how to get around this. I thought about temporary storage of getList in the session, but in principle it will work the same. What is the way out of this situation?

Class:

class Watched {
    const COOKIE_NAME = 'YOU_WATCHED';
    const EXPIRE = 30*24*3600;
    
    public static function getList() {
        $json = $_COOKIE[self::COOKIE_NAME];
        $array = json_decode($json, true);
        
        if(count($array)) {
            asort($array);
            return $array;
        }
        
        return [];
    }
    
    public static function add(int $productId): bool {
        if(!$productId) {
            return false;
        }
        
        $list = self::getList();
        $result = [];
        foreach($list as $product => $expireTime) {
            if($expireTime > time()) {
                $result[$product] = $expireTime;
            }
        }
        
        $result[$productId] = time() + self::EXPIRE;
        
        Core::setCookie(self::COOKIE_NAME, json_encode($result), self::EXPIRE + time());
        
        return true;
    }
    
    public static function remove(int $productId): bool {
        $list = self::getList();
        unset($list[$productId]);
        
        Core::setCookie(self::COOKIE_NAME, json_encode($list), self::EXPIRE + time());
        
        return true;
    }
}

Usage: Call add function

P.S. I do not want to store data in sessions or in sql. Need temporary storage, more "free" for the server.

php

cookies

setcookie

0 Answers

Your Answer

Accepted video resources