Reputation: 8773
I'm working on a e-commerce website in PHP and I would like to implement the following feature: if a user is not logged in, he can add products to the shopping cart and still have those products after login. Also, the feature must work the other way around: a user is logging in and then he adds products to the shopping cart.
I thought that a good way to do this is by using the session id, but after doing some test it turned out that this isn't the best way to do it.
Any ideeas?
Upvotes: 1
Views: 4006
Reputation: 449385
Why is using the session not the best way to do it? I'd say it is.
You could have a separate, session-based "non-logged in" shopping cart structure, an exact copy of the normal cart. If the user is not logged in, the products are stored there.
When the user logs in, you merge the non-logged in cart's contents with whatever items the user may already have in their user-speficic cart.
That point is also the place to deal with any conflicts that may arise from the product selection (like, a selected product being present in the logged in user's cart already).
Using cookies as recommended by @Codemwnci to either store the products, or a cart ID is a good idea too, because it allows the user to come back later and still have their cart contents, which you may want.
The same principle of merging will apply here as well, with an additional check whether the products in the cookie really are valid ones (they could have been removed since the user made their selection, or the user could have altered the cookie).
Upvotes: 6
Reputation: 54884
You can use cookies. Just store a unique identifier in the cookie, that represents the shopping basket. Regardless of whether the user is logged in or out, the Cookie identifier will still be the same, therefore the data will be persisted.
Upvotes: 1