Shopping cart persistence: $_SESSION or browser cookie?

前端 未结 6 615
天命终不由人
天命终不由人 2021-01-30 03:34

On an e-commerce site with no username/login to persist cart data, would it be better to use the PHP $_SESSION variable or a browser cookie to persist items in the shopping cart

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 03:47

    As pointed out by Xeoncross, it is very important to store any possible information for analysis. So one should not entirely rely on sessions and cookies.

    A possible approach is-

    Use sessions if not logged in

    If the user is not logged in, you can store and retrieve the cart items and wishlist items from session using $_SESSION in PHP

    Use database when logged in

    If the user is logged in then you can consider one of the two options -

    • Store the cart item or wishlist item in database alone
    • Store the cart item or wishlist item in database as well as in session (This will save some of your database queries)

    When user logs in

    When the user logs in, get all the cart items and wishlist items from the session and store it in the database.

    This will make the data persistent even if the user logs out or changes the machine but till the user has not logged in, there is no way to store the information permanently so it will not be persistent.

    Getting required data

    Whenever you are trying to access cart or wishlist do the following check -

    • If the user is not logged in then look into session
    • If the user is logged in, query database if you are storing in the database alone, otherwise you can just look into sessions if you are keeping session updated along with the database

提交回复
热议问题