What best practices should be followed when adding items to the shopping cart and calculating the total price in a PHP application?

When adding items to the shopping cart and calculating the total price in a PHP application, it is important to properly sanitize and validate user input to prevent any security vulnerabilities. Additionally, ensure that the price calculation is accurate and updated dynamically as items are added or removed from the cart. Finally, display the total price prominently to provide transparency to the user.

// Example PHP code for adding items to the shopping cart and calculating the total price

// Sanitize and validate user input
$item_name = filter_var($_POST['item_name'], FILTER_SANITIZE_STRING);
$item_price = filter_var($_POST['item_price'], FILTER_VALIDATE_FLOAT);

// Add item to the cart
$_SESSION['cart'][$item_name] = $item_price;

// Calculate total price
$total_price = 0;
foreach ($_SESSION['cart'] as $item => $price) {
    $total_price += $price;
}

// Display total price to the user
echo "Total Price: $" . number_format($total_price, 2);