I am trying to implement a shopping cart object for the user, storing a serialized version of the cart in the $_SESSION super global at the index 'user_cart', however I am running into an issue where the data I have stored at that index no longer exists when I move to a new page.
I do have session_start at the top of every page, and when I echo session_id(), I do get the same session id across multiple pages. In addition, when I echo $_SESSION on both pages, the page the object gets created on displays correctly as follows:
Array ( [user_cart] => Array ( [count] => 0 [items] => Array ( ) ) )
However, once I actually click on add to cart to order something, then navigate to my 'view cart' page, I get the following as my $_SESSION variable:
Array ( [user_cart] => )
Where it recognizes that my $_SESSION array has an index 'user_cart' however nothing is stored inside of it.
This ONLY happens if I add something to cart first, if I were to just go to the view cart page without adding anything to the cart, I get the same array printed as I did on the homepage where the session is created.
Here is some of the code I have in my 'add_to_cart_handler.php' file where I think the issue is arises:
$serialized=$_SESSION['user_cart'];
$cartobj=new ShoppingCart();
$cartobj->__unserialize($serialized);
$cartobj->addToCart($new_item_id, 1);
$_SESSION['user_cart']=$cartobj->__serialize();
header('Location: http://localhost/website/heroku/order.php');
Here is a snippet of both my __serialize() and __unserialize():
public function __serialize() {
return [
'count'=>$this->count,
'items'=>$this->serialize_items()
];
}
public function __unserialize(array $data) {
$this->count=$data[0];
$this->items=$this->unserialize_items($data[1]);
}
public function serialize_items() {
$serialized=array();
foreach($this->items as $item) {
$serialized[]=$item->__serialize();
}
return $serialized;
}
public function unserialize_items() {
$unserialized=array();
foreach($unserialized as $item){
$tmpItem=new CartItem();
$tmpItem->unserialize($item);
$unserialized[]=$tmpItem;
}
}
Where unserialize_items() and serialize_items() are essentially the same thing, but with the CartItem object.
EDIT:
It might be worth noting that my $_SESSION['user_cart'] has a value of null.