PHP LogoE-commerce Shopping Cart Application

An e-commerce shopping cart application is a fundamental component of any online retail store. It allows customers to collect items they wish to purchase before proceeding to checkout. The primary goal is to provide a seamless and intuitive way for users to manage their potential purchases.

Key functionalities typically include:
1. Adding Items: Users can add products from product pages to their cart. This usually involves specifying a quantity.
2. Removing Items: Users can remove individual items from their cart if they change their mind.
3. Updating Quantities: Users can adjust the quantity of items already in their cart.
4. Viewing Cart Contents: Displays a summary of all items currently in the cart, including product name, price, quantity, and subtotal for each item, as well as a grand total for the entire cart.
5. Emptying Cart: A clear all or empty cart option.
6. Persistence: The cart contents should ideally persist as the user navigates different pages or even returns to the site later (using sessions for guests, or a database for logged-in users).
7. Checkout Integration: Provides the final list of items and total price to the checkout process.

How it Works (Typical Implementation):
* Session-based (for Guests): For anonymous users, the shopping cart data is often stored in the user's PHP session (`$_SESSION`). This data typically includes product IDs, quantities, and sometimes prices/names for quick display. Session data is temporary and usually expires after a certain period of inactivity or when the browser is closed.
* Database-based (for Logged-in Users): For registered and logged-in users, cart data is often stored in a database (e.g., a `cart` table linked to a `users` table and `products` table). This allows the cart to persist across different devices, browser sessions, and even for an indefinite period, allowing users to build a wishlist-like cart over time. When a user logs in, their session-based cart (if any) might be merged with their database-stored cart.

Key Components in a PHP Application:
* Product Data: An array or database table storing product details (ID, name, price, image, etc.).
* Session Management: PHP's `$_SESSION` superglobal is crucial for storing cart data for guest users. `session_start()` must be called at the beginning of any script that interacts with sessions.
* Cart Logic: Functions or methods to handle adding, removing, updating, and calculating totals for cart items.
* User Interface: HTML forms and links to interact with the cart, displaying its contents to the user.

Example Code

<?php
session_start();

// --- Product Data (Hardcoded for simplicity) ---
$products = [
    1 => ['name' => 'Laptop Pro', 'price' => 1200.00],
    2 => ['name' => 'Wireless Mouse', 'price' => 25.50],
    3 => ['name' => 'Mechanical Keyboard', 'price' => 80.00],
    4 => ['name' => 'External SSD 1TB', 'price' => 95.00]
];

// --- Cart Initialization ---
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// --- Cart Functions ---

function addToCart($productId, $quantity = 1) {
    global $products;
    if (isset($products[$productId])) {
        if (isset($_SESSION['cart'][$productId])) {
            $_SESSION['cart'][$productId]['quantity'] += $quantity;
        } else {
            $_SESSION['cart'][$productId] = [
                'product_id' => $productId,
                'name' => $products[$productId]['name'],
                'price' => $products[$productId]['price'],
                'quantity' => $quantity
            ];
        }
        return true;
    }
    return false;
}

function removeFromCart($productId) {
    if (isset($_SESSION['cart'][$productId])) {
        unset($_SESSION['cart'][$productId]);
        return true;
    }
    return false;
}

function updateCartItemQuantity($productId, $quantity) {
    if (isset($_SESSION['cart'][$productId])) {
        $quantity = (int)$quantity;
        if ($quantity > 0) {
            $_SESSION['cart'][$productId]['quantity'] = $quantity;
            return true;
        } else {
            // If quantity is 0 or less, remove item
            return removeFromCart($productId);
        }
    }
    return false;
}

function getCartContents() {
    return $_SESSION['cart'];
}

function calculateCartTotal() {
    $total = 0;
    foreach ($_SESSION['cart'] as $item) {
        $total += $item['price'] * $item['quantity'];
    }
    return $total;
}

function clearCart() {
    $_SESSION['cart'] = [];
}

// --- Handle Actions ---
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $productId = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
    $quantity = isset($_GET['quantity']) ? (int)$_GET['quantity'] : 1;

    switch ($action) {
        case 'add':
            addToCart($productId, $quantity);
            break;
        case 'remove':
            removeFromCart($productId);
            break;
        case 'update':
            updateCartItemQuantity($productId, $quantity);
            break;
        case 'clear':
            clearCart();
            break;
    }
    // Redirect to prevent re-submitting form on refresh
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>E-commerce Shopping Cart</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; }
        .container { max-width: 900px; margin: auto; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h1, h2 { color: #333; }
        .product-list, .cart-list { margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px; }
        .product-item, .cart-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px dashed #eee; }
        .product-item:last-child, .cart-item:last-child { border-bottom: none; }
        .product-info, .cart-info { flex-grow: 1; }
        .product-actions, .cart-actions { margin-left: 20px; }
        .btn { background-color: #007bff; color: white; padding: 8px 12px; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; display: inline-block; font-size: 14px; }
        .btn-danger { background-color: #dc3545; }
        .btn-secondary { background-color: #6c757d; }
        .cart-total { font-size: 1.2em; font-weight: bold; text-align: right; margin-top: 20px; }
        .quantity-input { width: 50px; padding: 5px; border: 1px solid #ccc; border-radius: 4px; }
        form { display: inline-block; margin: 0; }
    </style>
</head>
<body>
    <div class="container">
        <h1>My Awesome Shop</h1>

        <h2>Available Products</h2>
        <div class="product-list">
            <?php foreach ($products as $id => $product): ?>
                <div class="product-item">
                    <div class="product-info">
                        <strong><?php echo htmlspecialchars($product['name']); ?></strong> - $<?php echo number_format($product['price'], 2); ?>
                    </div>
                    <div class="product-actions">
                        <a href="?action=add&product_id=<?php echo $id; ?>" class="btn">Add to Cart</a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <h2>Your Shopping Cart</h2>
        <div class="cart-list">
            <?php if (empty(getCartContents())): ?>
                <p>Your cart is empty.</p>
            <?php else: ?>
                <?php foreach (getCartContents() as $item): ?>
                    <div class="cart-item">
                        <div class="cart-info">
                            <strong><?php echo htmlspecialchars($item['name']); ?></strong> (x<?php echo $item['quantity']; ?>) - 
                            $<?php echo number_format($item['price'], 2); ?> each
                            = $<?php echo number_format($item['price'] * $item['quantity'], 2); ?>
                        </div>
                        <div class="cart-actions">
                            <form action="" method="get">
                                <input type="hidden" name="action" value="update">
                                <input type="hidden" name="product_id" value="<?php echo $item['product_id']; ?>">
                                <input type="number" name="quantity" value="<?php echo $item['quantity']; ?>" min="0" class="quantity-input">
                                <button type="submit" class="btn btn-secondary">Update</button>
                            </form>
                            <a href="?action=remove&product_id=<?php echo $item['product_id']; ?>" class="btn btn-danger">Remove</a>
                        </div>
                    </div>
                <?php endforeach; ?>
                <div class="cart-total">
                    Total: $<?php echo number_format(calculateCartTotal(), 2); ?>
                </div>
                <div style="text-align: right; margin-top: 15px;">
                    <a href="?action=clear" class="btn btn-danger">Clear Cart</a>
                    <a href="#" class="btn">Proceed to Checkout</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>