How can PHP sessions be effectively utilized in creating a secure shopping cart system?

To create a secure shopping cart system using PHP sessions, it is essential to store sensitive information such as the user's shopping cart items and total securely. This can be achieved by storing this data in session variables that are encrypted and validated before processing any transactions. Additionally, implementing measures such as CSRF tokens and SSL encryption can further enhance the security of the shopping cart system.

<?php
session_start();

// Add item to cart
if(isset($_POST['add_to_cart'])) {
    $product_id = $_POST['product_id'];
    $product_name = $_POST['product_name'];
    $product_price = $_POST['product_price'];
    
    $_SESSION['cart'][$product_id] = array(
        'name' => $product_name,
        'price' => $product_price
    );
}

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

// Display cart items
if(isset($_SESSION['cart'])) {
    foreach($_SESSION['cart'] as $product_id => $product) {
        echo $product['name'] . ' - $' . $product['price'];
        echo '<form method="post" action="">
                <input type="hidden" name="product_id" value="'.$product_id.'">
                <input type="submit" name="remove_from_cart" value="Remove">
              </form>';
    }
}
?>