codeigniter Cookie值重复

ru9i0ody  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(156)

目前,我有一个搜索栏,它将用户的搜索查询保存在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"}]
ia2d9nvy

ia2d9nvy1#

要防止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

}

相关问题