problems turning a serialized cookie into a session array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

problems turning a serialized cookie into a session array

Post by Swede78 »

I'm trying to make a shopping cart. I am using session variables to store the users cart information.

Everything was working as expected, until I tried to save their sessions as a cookie. Before attempting to add cookies, I add a product id and quantity to a array stored in a session variable. This all worked as I wanted. I decided that I wanted user's cart list to be saved as a cookie. So, after processing their cart (adding, updating, deleting from the session array), it also saves the session array as a cookie, like this:

// save as cookie
$Cart = serialize($_SESSION['Cart']);
setcookie("Cart", $Cart, time()+(60*60*24*30), "/");

This seems to work fine. However, when a user comes back, I check to see if their (session) cart is empty and if they have a (cookie) cart set. If so, I save the cookie as a session.

if( isset($_COOKIE['Cart']) )
{
$_SESSION['Cart'] = unserialize($_COOKIE['Cart']);
}

This works fine while testing it on my local machine, but when I test it on a real server, it doesn't work. It says that the $_SESSION['Cart'] is not an array. I tried declaring it as an array before setting it to = the cookie. That didn't work.

All the php.ini settings are identical to that of my local test machine. The only difference is that my machine is Win XP pro, and the server is Win NT. They're both PHP 4.3, MySQL 3.23 and IIS 5.

Any help would be appreciated. Thank you.
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

Post by Swede78 »

It seems as if it's having problems unserializing the cookie string:

echo cookie cart: a:1:{s:8:\"PRODUCTID\";i:1;}

echo cookie cart unserialized:
Notice: unserialize() [function.unserialize]: Error at offset 5 of 28 bytes in page.php on line 16


Looks like it's getting stuck on the "{" character. Maybe this info will help.
Post Reply