Cookie 值重复
目前我有一个搜索栏,它将用户的搜索查询保存在 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"}]
Currently I have a searchbar that saves the users search query inside a cookie. To do this I'm saving all the users inputs inside an array. Now the problem is that if the user types the same thing again, it gets duplicated and saves the duplicate value in the array as well. I want a way where the duplicate value doesn't get added to the cookie that has been set:
$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,'/');
}
}
Now this gives an output something like this:
[[[[{"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"}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了防止 cookie 被重复,您需要匹配 Cookie 名称及其内容
现在,如果您的 cookie 内容来自“动态”源,例如
用户输入
或rand()
函数,您可以将 cookie 内容存储在$_SESSION
中并使用它来验证 cookie 是否存在To prevent cookie being duplicated you need to match Cookie name and it's Content
Now if your cookie content come from "dynamic" source such as
user input
orrand()
function you can store the cookie content in a$_SESSION
and use that to verify cookie existance