struggling to understand some cookie/database shopping cart concepts - php

I am trying to get my head around how to correctly implement a shopping cart based on saving a cookie with a unique identifier to identify a users shopping cart in the database whether the user is logged in or as shopping a guest. I've tried to look at as many examples as i can, but i am not understanding it clearly enough.
Here's how i have it so far:
[Guest user]
Create cookie with unique id when user adds item to cart
Check for existing cart associated with cookie ID in database
If cart does not exist, create entry in DB table 'cart_id' with the cookie ID as session identifier
create entry in DB table 'cart_items' with the cookie ID as an identifier
[Logged in user]
Check for existing cart in DB table 'cart_id' associated with username and cookie ID
If cart exists, rewrite new cookie ID with cookie ID from database
If cart does not exist, assign username ID to table 'cart_id' with users unique cookie ID
Here is where i am having troubles:, all the previous is well and good, assuming the user hadn't only decided to login after filling their cart which is where i am going wrong. Here's what i have:
Check for existing cart in DB table 'cart_id' associated with username and cookie ID
If cart does not exist, assign username to 'cart_id' table
If cart already exists, rewrite new cookie ID with existing cookie ID stored in database
rewrite 'new' cart items(items chosen while not logged in) with the users stored cookie ID
Check for duplicate cart items from existing cart and new cart items
If duplicate items are found, delete old items and replace with new item quantities
etc etc So basically i dont think it's going too well, though i currently works okay, it seems i am going a really crappy way about it.
How can i better handle a registered users shopping cart if they choose to log in after they have filled their shopping cart? Will i need to have a separate table for guest users and registered users, how can i transfer a guest shopping cart list to the registered users shopping cart if they log in after they pick their cart?

I think you're better off at storing every ordered item (or the whole shopping cart content) locally, either through localStorage or cookie.
The way you do it, you're doing too much request on your DB. Why? Because you're assuming a cookie is something reliable, and in fact, it is not. So all of your operations using "cookie ID" are for nothing if the user chooses to reset his browser / delete his cookies.
There are many ways a cookie can be destroyed, at least it's harder with localStorage.
I would say : store it locally, and if logged, sync what has been saved locally with what is on the DB. But don't store unlogged users shopping carts on the DB : eventually you'll end up with orphans (no more cookie present for some reason), and you won't be able to understand why.

Related

PHP - Need to get the same thing using 3 very different id's from API

I need to be able to be able to get the same data from my database using 1 of 3 different ID's.
In this instance I am fetching shopping cart data using either a session_id (for guest users), account_id (for logged in users) or just by the cart's primary auto-incrementing key.
At the moment I have three GET API routes set up but I want to know if there's a more efficient way of accomplishing this
$router->get('carts/{id:i}', ['Controller\\CartController', 'getCartById']);
$router->get('carts/session-id/{sessionId:s}', ['Controller\\CartController', 'getCartBySessionId']);
$router->get('carts/account-id/{accountId:i}', ['Controller\\CartController', 'getCartByAccountId']);
A session_id is stored in a browser cookie with a TTL. A shopping cart will always have at least a session_id in the database but not always an account_id (signifying a guest user).
In this instance you are either logged in or a guest.
If the Cookie storing the session_id associated with a cart expires and you're not logged in we can assume that the cart has expired. If that guest user wants to add something to their cart again we will generate them a new one with a new session_id.
I think this chart explains things pretty well

Symfony4: How to transfer data to a new (logged in) session? e.g. shopping cart data

I want to allow guest visotors to store items in a shopping cart.
That cart should be taken into the new session, if that guest logs into an existing account.
Currently I save a session ID alongside cart data in my DB.
But as soon as a user logs into their account, the session ID is changed, so I don't have a way of moving the data from one session to the next.
What is the best way to (selectively) move data into a new session?
Try to check the documentation.
There are many type of session usage
https://symfony.com/doc/current/components/http_foundation/session_configuration.html

shopping cart and Session ID

I try to execute a shopping cart .In the beginning I save the selected products in an array SESSION
while the customer order doesn't complete.
But,my work was imperfect because I don't use the session ID and I don't insert the selected products
to database,therefore I can't management the sessions.
Now, I want to improve my code to get an unique sessionID for each customer.
I see more examples in this issue and here I want to know which better to use:
//session_id($_GET['PHPSESSID']); session_start();
$session_id=session_id('PHPSESSID');
-OR-
session_start();
$sessionID = $_COOKIE['PHPSESSID'];
then,I will save the selected products to db width this $session_id.
note that, I use a simple way to complete the customer order and store the selected
items to db, which is via customer email verification .after custmer verify his/her email
I want to go back him/her to a page that he/she can update his/her cart items or continue shopping.
here how to get the $session_id to do that successfully.
please guide me in this issue.Thanks
They both should return the same thing its just two different ways of referencing it. Although I would recommend against keying your users against session ids because the user can delete the cookie (which is where the id is stored) at anytime or it can expire and then you will have to create a whole new user which will cause you to lose all your records every time. I recommend keying your users against a primary key in the database.
Just store session id in cookie until (2 day for example) user return to site after email verification and then finish the order.

Storing shopping cart items into cookies and database

I am working on an e-commerce website. When the user is not logged into my website and clicks on "Buy Now" button, I want to store this information into the cookie as well as in the database. The table for the shopping cart looks like
SHOPPING_CART
(
sessionid int(10),
itemid int(10),
quantity tinyint(10) unsigned
date_added datetime
);
Primary key is: (sessionid, itemid)
When the user closes the browser then also the shopping cart items should be preserved. Now my question is the following:
When the user is not logged into my website, on what basis I should identify the user?
Should I store the information using the IP address? If yes then HOW? In this case sessionid in the above mentioned table would be the IP address of the user. Right?
Should I create a temporary session for each and every user who
visits my website and then store the information? If yes then HOW?
How can the shopping cart items be preserved even when the user
closes the browser window? Should I retrieve from database or
cookie?
Any other better method to store and retrieval of the information?
Note1: I can use plenty of Shopping Cart softwares/codes/libraries available. But I want to know: How to identify the user? And storing/retrieval of data.
Note2: The price of each item, ordering, shipping information all are stored in different tables.
All you can do is create a unique fake identity for the user
No. Multiple users may have the same IP address, and a single user may change its IP address
Yes. PHP will create a session for you as soon as you ask to start a session. You must associate an identity with this session. Just use a random number, or a UUID generator, or something like that to generate something unique and not easily guessable. Then store the identity in a cookie so that when the user comes back some time later, you can re-associate his identity with the new session.
I would just store the identity in the cookie. A cookie only holds a small amount of information, and may be modified by the user without you knowing it.
If the users don't log in, I don't see any other way.
the only thing you have to do is set the sessionid into a client-cookie.
if a customer returns and presents a sessionid cookie you update your cart table with his new sessionid (and set the new sessionid in the cookie).
session (that's what it is for)
no
'temporary session'?
the cart is in the database
better in what sense? secure? robust? user friendly?

Working with regenerating session id in PHP/CodeIgniter

I'm using CodeIgniter's Session class to manage my sessions for a cart/checkout system. The session data is being stored in the database and the session id is stored in a cookie. All cart information is retrieved via AJAX and is kept in the session, along with the session id.
Right now I am using the session id that PHP/CodeIgniter generates as a way to keep track of users. Users do not log in to the site and the store and the cart/checkout system are on different domains so this is the only thing that is tying them to their cart that is stored in the session/database. I use this session id in hidden fields on forms and as a parameter in links so that it gets sent to the server on any request (add item, remove item, view cart, etc...)
CodeIgniter lets you set a time for regenerating the session id, right now I have it set to 10 minutes. I had it at the default but that was too short because if the user sat at the page for too long, the session id that was dynamically written to the links and forms would be out of date and no longer tied to their cart data.
This is obviously not a great solution. What is the best way to allow for regenerating session ids at a lower interval but still keep users tied to their cart data even if the user waits 10+ minutes (without a page refresh) to do an action?
Don't use the session id's in the database. The cart should persist across sessions, so you need to store the cart in relation to the user, not the session. I also would not be putting the session id in fields as a hidden field. The benefit of sessions is you can store them server side.
Store the cart in the database, don't load the whole thing into session.
Method #1
A user can be given an "active" cart in the database.
User -> (has many) Cart
This cart is then updated by adding items to it
/cart/add/{id} -> Verify prices / quantities
This cart is not linked to the session, the session is only controlling which user is logged in. When they checkout the cart is set from "active" to "ordered" and a new "active" (but empty) cart is created. Carts will persist in the database between sessions, and a full history can be made available.
Method #2
Store the entire cart in session, not backed against the database. This would make some things simpler (adding / removing items aren't DB operations) but it also won't persist across sessions. When a user checks out write the cart to the database.

Categories