目前我有一個搜索欄,可以將用戶搜索查詢保存在 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"}]
uj5u.com熱心網友回復:
為防止 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 內容存盤在 a 中$_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://www.uj5u.com/qianduan/434143.html
