目前,我有一个搜索栏,可以将用户搜索查询保存在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"}]发布于 2022-02-28 05:44:22
为了防止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 input或rand()函数),则可以将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
}https://stackoverflow.com/questions/71290727
复制相似问题