What are some best practices for implementing a shopping cart function in PHP?
When implementing a shopping cart function in PHP, it is important to store the cart items in a session variable to maintain the cart's state across different pages. Additionally, use secure methods for adding, updating, and removing items from the cart to prevent security vulnerabilities. Finally, ensure that the cart functionality is user-friendly and intuitive for a seamless shopping experience.
// Start the session to store cart items
session_start();
// Add item to the cart
function addToCart($product_id, $quantity) {
$_SESSION['cart'][$product_id] += $quantity;
}
// Update item quantity in the cart
function updateCart($product_id, $quantity) {
$_SESSION['cart'][$product_id] = $quantity;
}
// Remove item from the cart
function removeFromCart($product_id) {
unset($_SESSION['cart'][$product_id]);
}