I'm storing data in cookie using serialize/unserialize function. Unserialize function does not working when i add new item to array.
$storedArr = array();
if(isset($_REQUEST['sendProductId'])){
$newItem = $_REQUEST['sendProductId'];
$storedArr[] = $_COOKIE['productID'];
array_push($storedArr, $newItem);
$cookie_name = 'productID';
setcookie($cookie_name, serialize($storedArr), time() + (86400 * 30));
}
$cookieData = $_COOKIE['productID'];
$data = unserialize($cookieData);
print_r($data);
Array ( [0] => [1] => 50 )
Array ( [0] => a:2:{i:0;N;i:1;s:2:"50";} [1] => 50 )
Please guide me where i'm wrong. Thanks
i see logical issue in your code, when you get data from cookie as it is serialized you have to first unserialize it then use
$storedArr[] = $_COOKIE['productID'];
change to
$storedArr = !empty($_COOKIE['productID']) ? unserialize( $_COOKIE['productID'] ):array();
it should solve your issue.