What are some best practices for implementing a shopping cart feature in a PHP project?

When implementing a shopping cart feature in a PHP project, it is important to use sessions to store the cart items, validate user input to prevent SQL injection and cross-site scripting attacks, and implement secure payment processing methods.

<?php
// Start the session
session_start();

// Add item to cart
if(isset($_POST['add_to_cart'])) {
    $product_id = $_POST['product_id'];
    $quantity = $_POST['quantity'];

    // Validate input
    $product_id = filter_var($product_id, FILTER_SANITIZE_NUMBER_INT);
    $quantity = filter_var($quantity, FILTER_SANITIZE_NUMBER_INT);

    // Add item to cart
    $_SESSION['cart'][$product_id] = $quantity;
}

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

    // Validate input
    $product_id = filter_var($product_id, FILTER_SANITIZE_NUMBER_INT);

    // Remove item from cart
    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>";
    }
}
?>