Add and remove favorite item with Cookie

1

I have the code to save the cookie by taking the id of the post

$id= "5100";
setcookie("itemfavorito", $id, time()+3600*24*30*12*1);

But I wanted a help that is how to do when the person is on another page with another id he saves together thus getting there in the cookie saved 5100/5101/5102 and so it goes ...

I know it should be with explode / implode , but I do not know how to apply it.

And also when removing the cookie from the page, what would it be like? To remove the right value from the page it would for example 5101

    
asked by anonymous 23.08.2018 / 15:15

1 answer

1
  

To "add" a value to a cookie, all you have to do is read the current value that was sent to you with the current request, add the new data, and set the result as a cookie with the same key.

On each page just change the value of the variable $id and include the page setar_cookie.php

Pages

$id= "5100";
include("setar_cookie.php");

setar_cookie.php

if(!isset($_COOKIE["itemfavorito"])) {
    setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/");
} else if (strpos($_COOKIE["itemfavorito"],$id)===false){
    $addId= $_COOKIE["itemfavorito"]."/".$id;
    setcookie("itemfavorito", $addId, time()+3600*24*30*12*1, "/");
}

To remove the right page value

$cookie= $_COOKIE['itemfavorito'];
//exemplo remover 5101

$id= join('/',array_diff(explode('/', $cookie), array('5101')));

setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/"); 

no ideone

  

OBS: The / (slash) in setcookie serves to indicate that it works for the whole site and not just the directory where it is being configured setcookie

If you want to keep the cookie always sorted

if(!isset($_COOKIE["itemfavorito"])) {
    setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/");
} else if (strpos($_COOKIE["itemfavorito"],$id)===false){
        $addId= $_COOKIE["itemfavorito"]."/".$id;
        $array= explode("/",$addId);
        sort($array);
        $joinId= join('/',$array); 
        setcookie("itemfavorito", $joinId, time()+3600*24*30*12*1, "/");
}

And if you have a "5101" ID added and if you are adding another "510"

  

In this case we can use:

setar_cookie.php

$tags = $_COOKIE["itemfavorito"];
$tagsArray = explode('/', $tags);

if(!isset($_COOKIE["itemfavorito"])) {
    setcookie("itemfavorito", $id, time()+3600*24*30*12*1, "/");
} else if (!in_array($id, $tagsArray)) {
        $addId= $_COOKIE["itemfavorito"]."/".$id;
        $array= explode("/",$addId);
        sort($array);
        $joinId= join('/',$array); 
        setcookie("itemfavorito", $joinId, time()+3600*24*30*12*1, "/");
}
    
23.08.2018 / 21:03