简体   繁体   中英

How do I use cookies to store shopping cart content?

So I have this little shopping cart included into every page of my website via php include method.

The structure of the shopping cart looks like this:

<div class="shopping_cart">
<h4 class="sc_title">Shopping cart</h4>
<form action="../scripts/sc_order.php" method="post">
    <div class="sc_content">
        <div class="product">Product 1</div>
        <div class="product">Product 3</div>
        <div class="product">Product 5</div>
    </div>
    <input type="submit" value="Submit order" />
    <div class="sc_button">Clear cart</div>
</form>

But when I go from page to page, the products which have been added from one page disappear from the cart upon entering a new one.

How do I use cookies to remember the cart content?

Add your $_POST/$_GET data into the cart array.

$cart = [];

If your moving to a new page then serialize cart array and add to the setcookie() function. Doing it this way you can have multiple items in your cart under one cookie.

setcookie('cart', 'serialize($cart)', time() + 60*100000, '/'); 

You can then access the cart array by using unserialize() on the cookie.

$newarray = unserialize($_COOKIE['cart']);

You can then expire the cookie after the purchase is complete.

setcookie('cart', 'serialize($cart)', time() - 60*100000, '/');

As @Marc B said, it may be worth looking into sessions if you only want the users to have the cart saved during that browser session but it's up to you. Just make sure you do not save any passwords or secure information as they are easily accessed client side.

I also recommend looking into the other parameters which have not been explained here.

http://php.net/manual/en/features.cookies.php

It would be a good idea to read up on the $_SESSION superglobal: http://php.net/manual/en/reserved.variables.session.php

You could also try HTML5 localstorage: https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage

Until the checkout process you do not have the User ID. So, you need to handle this using Session or combined of Session and Cookies . Once user land your web page, you have a session value store this. Write the Session value / ID in Cookies too. Now your Key is Session, write Cookies as Array, it would be like this: SID, Cart_id, last_update,Item_added etc. So, from any page you can keep update user cart. Once Checkout made, you might going to ask the user to login or signup. So at this stage you have the User ID. Insert the Array written at Cookies at your Table. It's a easy process to manage. This process also simplified your Inventory, Stock manage and reporting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM