programmer
programmer

Reputation: 39

How to expire cart after a limited time

I need Help on how to expire a shopping cart
Suppose we have a shopping cart in a e-commerce website, and a user adds a product to his shopping cart the problem is that from the inventory we should decrement the quantity of that product because it’s being held by a user.
The idea is we implement a timer in the shopping cart when that timer expires, the user doesn’t hold that product anymore.

My questions are :

Hope my explanation was clear. Thank you for your time.

Upvotes: 0

Views: 508

Answers (1)

Andrew Larsen
Andrew Larsen

Reputation: 1267

One example using session, don't forget that the session will expire when the browser is closed. If you want more persistant data storage, use cookies or localStorage.

<?php

/* Constants */
define('EXPIRATION_TIME', 30); // minutes

/* Dummy variables */
$productAdded = true;

/* Start session */
session_start();

/* Check timer */
if (isset($_SESSION['timer']) && $_SESSION['timer'] < time()) {

    /* 
        30 min have gone by and the user has not added more products
        to the cart, lets empty the cart and reset the timer
    */

    unset($_SESSION['cart']);
    unset($_SESSION['timer']);
}

/* Add product */
if ($productAdded) {

    /* Increase timer */
    $_SESSION['timer'] = (time() + (EXPIRATION_TIME * 60));

    /* Add product to cart, and all other tasks */
    if (!isset($_SESSION['cart']))
        $_SESSION['cart'] = array();

    $_SESSION['cart'][] = array(
        'id' => 17,
        'name' => 'Fancy shampoo',
        'quantity' => 1337
    );
}

?>

Upvotes: 1

Related Questions