Forum Moderators: coopster

Message Too Old, No Replies

Mysterious resetting cookie

         

mrnoisy

3:29 am on Oct 3, 2005 (gmt 0)

10+ Year Member



I'm using the following code at the top of all the relevant pages in a shopping cart site. The cookie gets stored in a database with any items that are added to the cart, to track what a user has added.

if(!isset($HTTP_COOKIE_VARS['cart_id'])) {
$cart_id = md5(uniqid(rand()));
setcookie("cart_id", $cart_id, time() + 14400);
} else {
$cart_id = $HTTP_COOKIE_VARS['cart_id'];
}

It works fine for me and most users, on both IE6 and Firefox. But for some users, when changing pages or going to the cart, it seems that a new cookie is getting set and resetting the items.

For example, on the red widget page, I add 1 to the cart. Then I visit the blue widget page and find that the cart is empty. I add 2 blue widgets to the cart, which display. Then I go back to the red widget page which displays the 1 red widget that I added before. It should by now be showing 3 items, one red and two blue widgets. When I go to checkout, the cart is empty.

It seems to me that a new cookie should only be set if there isn't one already.

jatar_k

4:03 pm on Oct 3, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



it sounds almost like it is randomly resetting the cart_id which means your!isset isn't always getting evaluated properly.

Have you been able to reproduce it consistently?

is it anything to do with switching from http to https?

you could also try setting the domain explicitly, that might be the issue

mrnoisy

9:59 pm on Oct 3, 2005 (gmt 0)

10+ Year Member



I have not been able to create the problem on any of my machines, but I've talked some customers through it on the phone, and they have the problem consistently.

It's nothing to do with switching to https, because the error occurs before any of that happens.

How would I set the domain explicitly?

jatar_k

2:18 pm on Oct 4, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



if you look at the definition for setcookie [php.net]

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )

you are using the first three vars name, value, expire but you could also use path and domain. There are examples on the page I linked to.