How can the use of sessions in PHP improve the management of a shopping cart feature in an online shop script?
Using sessions in PHP can improve the management of a shopping cart feature in an online shop script by allowing the cart data to persist across different pages and visits. This ensures that the items added to the cart remain in place until the user completes the purchase or removes them. By storing the cart data in session variables, the shopping cart functionality becomes more robust and user-friendly.
// Start the session
session_start();
// Add a product to the cart
if(isset($_POST['add_to_cart'])){
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
// Check if cart session variable exists, if not, create it
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
// Add the product to the cart
$_SESSION['cart'][$product_id] = $quantity;
// Redirect to the shopping cart page
header('Location: shopping_cart.php');
exit;
}
// Remove a product from the cart
if(isset($_GET['remove_from_cart'])){
$product_id = $_GET['remove_from_cart'];
// Check if the product is in the cart
if(isset($_SESSION['cart'][$product_id])){
unset($_SESSION['cart'][$product_id]);
}
// Redirect to the shopping cart page
header('Location: shopping_cart.php');
exit;
}