Search code examples
phpcookiesbase64setcookie

How to store array in cookie by PHP?


On my website I want to build a simple watchlist for customers to favorite some products without need of creating account.

I read about this topic that it is not possible directly but by base64 encoding to store to cookie.

This script is toggled by button click. If product is already on watchlist it will be removed and if it is not on watchlist it will be added.

This is what I've tried:

$p = "123456789"; // some product id    

$a = isset($_COOKIE['fav']) ? unserialize(base64_decode($_COOKIE['fav'])) : [] ;

if($p!==in_array($a)){
  $a[] = $p;
} else {
  if(($key=array_search($p,a))!==false){
    unset($a[$key]);
  }
}

$b = base64_encode(serialize($a));
setcookie('fav',$b,time()+3600*24,'/');

But the cookie don't get set.


Solution

  • if (!in_array($p, $a)) { // <- this is the right syntax
      $a[] = $p;
    } else {
      if (($key = array_search($p, a)) !== false) {
        unset($a[$key]);
      }
    }
    

    And if you want it type-save it's

    if (!in_array($p, $a, true))