Home > front end >  Cookie values getting duplicated
Cookie values getting duplicated

Time:02-28

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"}]

CodePudding user response:

To prevent cookie being duplicated you need to match Cookie name and it's Content

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

}

Now if your cookie content come from "dynamic" source such as user input or rand() function you can store the cookie content in a $_SESSION and use that to verify cookie existance

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

}
  • Related