Cookie 值重复

Cookie values getting duplicated

目前我有一个将用户搜索查询保存在 cookie 中的搜索栏。为此,我将所有用户输入保存在一个数组中。现在的问题是,如果用户再次键入相同的内容,它就会重复并将重复的值保存在数组中。我想要一种不会将重复值添加到已设置的 cookie 中的方法:

$input_search = json_decode(($this->input->post('keyword_search')));

    if(isset($input_search))
    foreach($input_search as $searchvals){
        $searchvals->name = $searchvals->value;
        unset($searchvals->value);
        $searchval = json_encode($searchvals);

        if (!isset($_COOKIE['lpsearch_history'])){  
                setcookie('lpsearch_history',$searchval,time() +3600 *365,'/'); 
            }else {
                $locations[] = json_decode($_COOKIE['lpsearch_history'], true);
                $arrsearchval = json_decode($searchval, true);
                if(!in_array($arrsearchval, $locations))
                    $locations[] = $arrsearchval;
                $areas = json_encode($locations);
                setcookie('lpsearch_history',$areas,time() +3600 *365,'/');
            }
    }

现在输出如下:

[[[[{"type":"community","devslug":"downtown-dubai","name":"Downtown Dubai"}],
{"type":"community","devslug":"downtown-dubai","name":"Downtown Dubai"}],    
{"type":"community","devslug":"palm-jumeirah","name":"Palm Jumeirah"}],    
{"type":"community","devslug":"palm-jumeirah","name":"Palm Jumeirah"}]

为防止 cookie 被复制,您需要匹配 Cookie 名称及其内容

if (isset($_COOKIE['Cookie_Name']) && $_COOKIE['Cookie_Name'] == "Cookie_Content") {

// do nothing cookie already existed and content match

} else { 

setcookie('Cookie_Name', 'Cookie_Content', time()+1800, "/"); 
// create cookie which expire 30mins

}

现在,如果您的 cookie 内容来自“动态”来源,例如 user inputrand() 函数,您可以将 cookie 内容存储在 $_SESSION 中并使用它来验证 cookie 是否存在

if (isset($_COOKIE['Cookie_Name']) && $_COOKIE['Cookie_Name'] == $_SESSION['cookie_content']) {

// do nothing cookie already existed and content match

} else {

$cookie_content = rand(1000,999999); // random cookie content 
$_SESSION['cookie_content'] = $cookie_content; 
setcookie('Cookie_Name', $cookie_content, time()+1800, "/"); 
// create cookie which expire 30mins

}