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);
Related Questions
- How can PHP_AUTH_USER and PHP_AUTH_PW variables be set by the web server or PHP itself, and what implications does this have for authentication scripts?
- What is the best practice for fetching multiple values from a MySQL database in PHP and storing them in an array?
- How can PHP be used to dynamically generate pop-up windows for displaying images?