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
}

相关内容

  • 没有找到相关文章

最新更新