How can PHP sessions be effectively utilized in a shopping cart system to track user interactions?

To effectively utilize PHP sessions in a shopping cart system to track user interactions, you can store the cart items in the session variables. Each time a user adds or removes an item from the cart, update the session variable accordingly. This allows the cart items to persist across different pages and interactions until the user completes the checkout process.

// Start the session
session_start();

// Add item to the cart
if(isset($_POST['add_to_cart'])) {
    $product_id = $_POST['product_id'];
    
    if(!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
    }
    
    $_SESSION['cart'][$product_id] = 1;
}

// Remove item from the cart
if(isset($_POST['remove_from_cart'])) {
    $product_id = $_POST['product_id'];
    
    if(isset($_SESSION['cart'][$product_id])) {
        unset($_SESSION['cart'][$product_id]);
    }
}

// Display cart items
if(isset($_SESSION['cart'])) {
    foreach($_SESSION['cart'] as $product_id => $quantity) {
        echo "Product ID: $product_id, Quantity: $quantity <br>";
    }
}